Serilog - how to make custom console output format?

寵の児 提交于 2020-04-13 06:56:00

问题


I am using Serilog with serilog-sinks-console in my C# project and I am wondering how can I modify format of console output without creating whole new formatter. I just need to adjust one thing info java (slf4j/logback) like format.

From this:

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

into this:

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

or just this simple format:

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

回答1:


Thanks for the direction to @Ruben Bartelink. If anyone else will be wondering how to do such thing here is the simple example:

Enricher:

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

then usage:

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


来源:https://stackoverflow.com/questions/50651694/serilog-how-to-make-custom-console-output-format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!