gpt4 book ai didi

c# - .Net core 2.0 控制台应用程序的日志记录和配置?

转载 作者:IT王子 更新时间:2023-10-29 04:38:00 26 4
gpt4 key购买 nike

以下代码出现错误。为 .Net Core 2.0 控制台应用程序设置日志记录和配置管理的正确方法是什么?

Error CS1061 'LoggerFactory' does not contain a definition for 'AddConsole' and no extension method 'AddConsole' accepting a first argument of type 'LoggerFactory' could be found (are you missing a using directive or an assembly reference?)

Error CS1503 Argument 2: cannot convert from 'Microsoft.Extensions.Configuration.IConfigurationSection' to '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());
}
}
}
}

最佳答案

看起来您可能缺少一些依赖项:

  1. Microsoft.Extensions.Logging.Console ,它提供了 AddConsole扩展方法。
  2. Microsoft.Extensions.Options.ConfigurationExtensions ,它提供了 Configure<T>您似乎缺少扩展方法。

在 .NET Core 可执行文件中配置服务方面,Andrew Lock 有一个 post关于 .NET Core 的第一个版本的主题。随着 .NET Core 2 最近的到来,其中一些内容可能已经过时,但值得一读。

关于c# - .Net core 2.0 控制台应用程序的日志记录和配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45927107/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com