2

我想在“TODO”行中使用记录器,因为我需要在添加“AddJsonConfigurationSourceDecryption”方法时记录,有没有办法获取记录器?

登录 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>();
    }
}
4

1 回答 1

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");
                    ...
                    })
于 2020-10-26T11:10:24.037 回答