【问题标题】:How to do I output SeriLog json properties onto a .txt format如何将 SeriLog json 属性输出为 .txt 格式
【发布时间】:2021-08-11 22:41:53
【问题描述】:

参考
https://www.youtube.com/watch?v=_iryZxv8Rxw&t=2105s&ab_channel=IAmTimCorey (44:00)
https://github.com/serilog/serilog/wiki/Enrichment C# SeriLog 输出模板格式

我想要什么
我希望将视频中看到的属性 SourceContext 显示到我的 .txt 输出中
但问题是视频是在 Json 文件中完成的,我不确定如何将其应用于
C# 和 .txt 上下文。

我有什么
没什么,只是基本的。我想知道我缺少什么来获得它的输出。

#region Logger
            Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Verbose()
            .Enrich.WithProcessId()
            .Enrich.WithProcessName()
            .Enrich.WithThreadId()
            .Enrich.FromLogContext()
            .WriteTo.Console(restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information)
            .WriteTo.File("log.txt",
                restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Verbose,
                rollingInterval: RollingInterval.Day,
                rollOnFileSizeLimit: true,
                outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj} {Exception:1}{NewLine}")
            .CreateLogger();
            Log.Verbose("Test Verbose");
            Log.Debug("Test Debug.");
            Log.Information("Test Info.");
            Log.Warning("Test Warning!");
            Log.Error("Test Error!!");
            Log.Fatal("Test Fatal!!");
            #endregion

【问题讨论】:

    标签: c# .net serilog


    【解决方案1】:

    如果你想在 C# 上下文中使用它。请注意,多线程可能是随之而来的问题。

    https://gist.github.com/litetex/b88fe0531e5acea82df1189643fb1f79

    【讨论】:

      【解决方案2】:

      control event formatting 可以通过指定输出模板字符串(根据您的示例)或提供自定义 ITextFormatter 来进行格式化(您链接的视频中显示的示例)。

      在您的示例中,您可以在输出模板中简单地包含 SourceContext

      "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {SourceContext} {Message:lj}{NewLine}{Exception}"
      

      如果您希望日志事件中出现所有属性(包括SourceContext),您可以改用{Properties}

      "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Properties} {Message:lj}{NewLine}{Exception}"
      

      【讨论】:

      • 我确实试过了,但它没有出现在 .txt 上,只有 .json。
      猜你喜欢
      • 1970-01-01
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 1970-01-01
      • 2018-07-13
      • 1970-01-01
      • 2016-09-24
      相关资源
      最近更新 更多