ASP.NET Core在Program.cs中创建日志

时间:2018-11-12 13:14:46

标签: asp.net-core loggerfactory

我想在“ TODO”行中使用记录器,因为添加“ AddJsonConfigurationSourceDecryption”方法时需要记录日志,有什么方法可以获取记录器?

Logging in ASP.NET Core

  public class Program
{

    public static void Main(string[] args)
    {
        ILogger<Program> logger = null;
        try
        {
            var host = CreateWebHostBuilder(args).Build();

            ApplicationLogging.LoggerFactory = host.Services.GetRequiredService<ILoggerFactory>();
            logger = host.Services.GetRequiredService<ILogger<Program>>();

            logger.LogInformation("start thin API service...");
            host.Run();
        }
        catch (Exception ex)
        {
            logger?.LogError(ex, "Stopped program because of exception");
            throw;
        }
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        return WebHost.CreateDefaultBuilder(args)
            .UseKestrel(option => option.AddServerHeader = false)
            .ConfigureLogging((host, builder) => { builder.SetMinimumLevel(LogLevel.Trace); })
            .UseNLog()
            .ConfigureServices(services => services.AddAutofac())
            .ConfigureAppConfiguration((context, builder) =>
            {
                //TODO: Logger.............
                builder.SetBasePath(Directory.GetCurrentDirectory());
                builder.AddJsonConfigurationSourceDecryption();
            })
            .UseStartup<Startup>();
    }
}

1 个答案:

答案 0 :(得分:0)

@ 0xced在这里回答了这个问题 How to create a LoggerFactory with a ConsoleLoggerProvider?

从dotnetcore3.1开始,代码可以通过这种方式编写

private static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args).ConfigureAppConfiguration(
                (hostContext, config) =>
                    {
                        var loggerFactory = LoggerFactory.Create(
                            builder => 
                                {
                                    builder
                                        .AddFilter("Microsoft", LogLevel.Warning)
                                        .AddFilter("System", LogLevel.Warning)
                                        .AddFilter("YourProgramNamespsace.Program", LogLevel.Debug)
                                        .AddConsole();
                                });
                        var logger = loggerFactory.CreateLogger<Program>();
                        logger.LogInformation("Hello from ConfigureAppConfiguration");
                    ...
                    })