SeriLog和.NET Core 2.1 HostBuilder配置?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (330)

我正在使用.NET Core 2.1 HostBuilder类来设置和运行GRPC服务器,并且无法正确配置SeriLog,以便它可以被.NET Core日志管道使用,并在我的应用程序的其他地方可用(通过依赖项注入)。

class Program
{
    private static async Task Main(string[] args)
    {
        var hostBuilder = new HostBuilder()
            .ConfigureServices((hostContext, services) =>
            {
                services.AddSingleton<ILogger>(BuildLogger);

                // other services here 
            })
            .ConfigureLogging((hostContext, loggingBuilder) =>
                loggingBuilder.AddSerilog(dispose: true));

        await hostBuilder.RunConsoleAsync();
    }

    private static ILogger BuildLogger(IServiceProvider provider)
    {

        // create a (global) logger
        Log.Logger = new LoggerConfiguration() 
            ...
            .CreateLogger();

        return Log.Logger;
    }
}

问题是我需要打电话到loggingBuilder.AddSerilog()使用单例ILogger这是在上面的几行DI服务配置中注册的。

提问于
用户回答回答于

试试:

  public static IHost BuildHost(string[] args) =>
    new HostBuilder()
        .ConfigureServices(services => services.AddSingleton<IHostedService, PrintTimeService>())
        .UseSerilog() // <- Add this line
        .Build();
用户回答回答于

根据REPOfor.NET核心2.0+的文档,调用AddSerilog()关于所提供的loggingBuilder并确保首先配置Serilog:

//...

private static async Task Main(string[] args) {

    Log.Logger = new LoggerConfiguration()
        //...
        .CreateLogger();

    var hostBuilder = new HostBuilder()
        .ConfigureServices((hostContext, services) => {        
            services.AddLogging(loggingBuilder =>
                loggingBuilder.AddSerilog(dispose: true));

            // other services here 
        });

    await hostBuilder.RunConsoleAsync();
}

//...

扫码关注云+社区

领取腾讯云代金券