使用Serilog(或任何结构化日志库)的Steeltoe动态日志记录配置

时间:2019-02-25 15:54:40

标签: asp.net-core serilog steeltoe

这可能是重复的 How to set Steeltoe Dynamic Logging works with 3rd party loggers as Serilog?。我想利用Steeltoe动态日志记录配置(将帮助我动态地调整日志级别而无需重新部署),并希望使我的日志语句更加结构化。因此,我决定看看Serilog。这是我的代码

public class Program
    {

        /// <summary>
        /// Application entry point.
        /// </summary>
        /// <param name="args">arguments.</param>
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static IWebHost BuildWebHost(string[] args) =>
                    WebHost.CreateDefaultBuilder(args)
                        .UseStartup<Startup>()
            .ConfigureAppConfiguration((hostContext, config) =>
            {
                config.AddCloudFoundry();
            })
            .ConfigureLogging((context, builder) =>
            {
                // We need to clear providers which are added by CreateDefaultBuilder(). 
                // Please refer https://github.com/aspnet/Logging/issues/648. Otherwise log entries will be duplicated 
                // since AddDynamicConsole again add console logger
                builder.ClearProviders();
                if (context.HostingEnvironment.IsDevelopment())
                {
                    builder.AddDebug();
                }
                builder.AddDynamicConsole();
            })
            .UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
                 .ReadFrom.Configuration(hostingContext.Configuration)
                 .Enrich.FromLogContext()
                 .WriteTo.Console(outputTemplate:
                 "[{Level:u3}] [{Properties}] {Message}{NewLine}{Exception}")
            .WriteTo.Trace())
            .Build();
    } 

但这不能按预期工作。在PCF Apps管理器中,除了“默认”之外,我看不到任何日志记录提供程序。如果我取消评论

  

UseSerilog()

他们也回来了。顺便说一句,我不想​​将自己限制在Serilog上,而NLog可以做到这一点(听说它也支持结构化日志记录)?还是最欢迎将结构化日志记录与动态日志记录配置相结合的其他想法

1 个答案:

答案 0 :(得分:0)

Steeltoe现在通过dev branch MyGet feed中的Steeltoe.Extensions.Logging.SerilogDynamicLogger对Serilog有了初步支持。源代码和单元测试位于this repository中,我们欢迎您的反馈!

使用新的NuGet软件包,您应该可以做到

new WebHostBuilder()
  .ConfigureLogging((builderContext, loggingBuilder) =>
  {
    loggingBuilder.AddConfiguration(builderContext.Configuration.GetSection("Logging"));

    // Add Steeltoe Dynamic Serilog provider
    loggingBuilder.AddSerilogDynamicConsole();
  })

然后按照与现有动态记录器相同的方式进行操作。