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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容