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

前端之家收集整理的这篇文章主要介绍了c# – .Net core 2.0控制台应用程序的日志记录和配置?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下代码得到了错误.为.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());
            }
        }
    }
}

解决方法

它看起来你可能会遗漏几个依赖项:

> Microsoft.Extensions.Logging.Console,它提供AddConsole扩展方法.
> Microsoft.Extensions.Options.ConfigurationExtensions,其提供配置< T>您似乎缺少扩展方法.

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

猜你在找的.NET Core相关文章