c# Serilog 动态绑定 模板属性

官网的文档有误,所以做一下记录,避免入坑。
https://github.com/serilog/serilog/wiki/Enrichment#the-logcontext


        public static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json")
                                .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", true)
                                .Build();

            Log.Logger = new LoggerConfiguration()
                        .ReadFrom.Configuration(configuration)
                        // .Enrich.WithProperty("MyVersion", "1.0.2")
                        .Enrich.FromLogContext()
                        .CreateLogger();
            try
            {

                Log.Information("No contextual properties");

                using (LogContext.PushProperty("A", "A_Value"))
                {
                    Log.Information("Carries property {A} = 1");

                    using (LogContext.PushProperty("A", "A_Value2"))
                    using (LogContext.PushProperty("B", "B_Value"))
                    {
                        Log.Information("Carries {A} = 2 and {B} = 1");
                    }

                    Log.Information("Carries property {A} = 1, again");
                }

            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush(); // 释放资源
            }

        }

运行结果:

image.png

你可能感兴趣的:(c# Serilog 动态绑定 模板属性)