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

时间:2018-06-01 22:25:18

标签: serilog

我在我的C#项目中使用Serilogserilog-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

2 个答案:

答案 0 :(得分:1)

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

Enricher:

func application(_ sender: NSApplication, openFiles filenames: [String]) {
        if let window = NSApp.mainWindow, let vc = window.contentViewController as? ViewController {
            vc.openThese(files: filenames)
        }
    }

然后使用:

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));
  }
}

答案 1 :(得分:0)

F#莫吉米尔的回答即兴(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"
                | _ -> ()