Serilog - 如何制作自定义控制台输出格式?

Serilog - how to make custom console output format?

我在我的 C# 项目中使用 Serilog with serilog-sinks-console,我想知道如何在不创建全新格式化程序的情况下修改控制台输出的格式。我只需要调整一件事信息 java (slf4j/logback) 比如格式。

来自这里:

00:19:49 [DBG] Microsoft.AspNetCore.Hosting.Internal.WebHost - App starting
00:19:49 [DBG] Microsoft.AspNetCore.Hosting.Internal.WebHost - App started

进入这个:

00:19:49 [DBG] m.a.h.i.WebHost - App starting
00:19:49 [DBG] m.a.h.i.WebHost - App started

或者只是这个简单的格式:

00:19:49 [DBG] WebHost - App starting
00:19:49 [DBG] WebHost - App started

感谢@Ruben Bartelink 的指导。如果其他人想知道如何做这样的事情,这里有一个简单的例子:

丰富剂:

class SimpleClassEnricher : ILogEventEnricher
{
  public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
  {
    var typeName = logEvent.Properties.GetValueOrDefault("SourceContext").ToString();
    var pos = typeName.LastIndexOf('.');
    typeName = typeName.Substring(pos + 1, typeName.Length - pos - 2);
    logEvent.AddOrUpdateProperty(propertyFactory.CreateProperty("SourceContext", typeName));
  }
}

然后用法:

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .Enrich.With(new SimpleClassEnricher())
    .WriteTo.Console(outputTemplate: "{Timestamp:HH:mm:ss} [{Level:u3}] {SourceContext} - {Message:lj}{NewLine}{Exception}")
    .CreateLogger();

F# 模仿 Mojmir 的回答(HT @Kostas Rontogiannis):

    /// Converts SourceContext which is the fully qualified type name to a short version, using just the type name.
    type SourceContextShortEnricher () =
        interface Serilog.Core.ILogEventEnricher with
            member __.Enrich(logEvent : Serilog.Events.LogEvent, lepf : Serilog.Core.ILogEventPropertyFactory) =
                match logEvent.Properties.TryGetValue "SourceContext" with
                | true, (:? Serilog.Events.ScalarValue as v) when v <> null && v.Value <> null ->
                    let typeName =
                        string v.Value
                        |> fun s -> match s.LastIndexOf("[[") with -1 -> s | pos -> s.Substring(0, pos)
                        |> fun s -> match s.LastIndexOf('.') with -1 -> s | idx when s.Length = idx - 1 -> s | idx -> s.Substring(idx + 1)
                    logEvent.AddPropertyIfAbsent(lepf.CreateProperty("SourceContextShort", typeName))
                    logEvent.RemovePropertyIfPresent "SourceContext"
                | _ -> ()