以下代码出错。为.Net Core 2.0控制台应用程序设置日志记录和配置管理的正确方法是什么?
错误CS1061' LoggerFactory'不包含' AddConsole'的定义没有扩展方法' AddConsole'接受类型' LoggerFactory'的第一个参数。可以找到(你错过了使用指令或程序集引用吗?)
错误CS1503参数2:无法转换为' Microsoft.Extensions.Configuration.IConfigurationSection'到' System.Action'
class Program
{
static void Main(string[] args)
{
var services = new ServiceCollection();
ConfigureServices(services);
var serviceProvider = services.BuildServiceProvider();
var app = serviceProvider.GetService<Application>();
Task.Run(() => app.Run()).Wait();
}
private static void ConfigureServices(IServiceCollection services)
{
ILoggerFactory loggerFactory = new LoggerFactory()
.AddConsole() // Error!
.AddDebug();
services.AddSingleton(loggerFactory); // Add first my already configured instance
services.AddLogging(); // Allow ILogger<T>
IConfigurationRoot configuration = GetConfiguration();
services.AddSingleton<IConfigurationRoot>(configuration);
// Support typed Options
services.AddOptions();
services.Configure<MyOptions>(configuration.GetSection("MyOptions")); // Error!
services.AddTransient<Application>();
}
private static IConfigurationRoot GetConfiguration()
{
return new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddXmlFile("App.config", optional: true).Build();
}
public class MyOptions
{
public string Name { get; set; }
}
public class Application
{
ILogger _logger;
MyOptions _settings;
public Application(ILogger<Application> logger, IOptions<MyOptions> settings)
{
_logger = logger;
_settings = settings.Value;
}
public async Task Run()
{
try
{
_logger.LogInformation($"This is a console application for {_settings.Name}");
}
catch (Exception ex)
{
_logger.LogError(ex.ToString());
}
}
}
}
答案 0 :(得分:15)
看起来你可能会遗漏几个依赖项:
Microsoft.Extensions.Logging.Console
,提供active
扩展方法。Microsoft.Extensions.Options.ConfigurationExtensions
,它提供了您似乎缺失的AddConsole
扩展方法。在.NET Core可执行文件中配置服务方面,Andrew Lock对第一版.NET Core的主题有post。其中一些可能已经过时了.NET Core 2最近的到来,但它值得一读。
答案 1 :(得分:13)
在Kirk Larkins的基础上回答(确保安装了nuget软件包,Microsoft.Extensions.Options.ConfigurationExtensions
,Microsoft.Extensions.Logging.Console
和Microsoft.Extensions.Logging.Debug
)然后您可以简化日志记录配置并跳过loggerFactory的声明传递ILoggerBuilder
到.AddLogging()
:
public static IServiceProvider ConfigureServices(IServiceCollection serviceCollection)
{
//ILoggerFactory loggerFactory = new LoggerFactory()
// .AddConsole()
// .AddDebug();
serviceCollection
.AddLogging(opt =>
{
opt.AddConsole();
opt.AddDebug();
})
.AddTransient<IFooService, FooService>();
/*... rest of config */
var serviceProvider = serviceCollection.BuildServiceProvider();
return serviceProvider;
}