Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serilog - how to make custom console output format?

Tags:

serilog

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
like image 311
mojmir.novak Avatar asked Jun 01 '18 22:06

mojmir.novak


1 Answers

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();
like image 115
mojmir.novak Avatar answered Sep 17 '22 13:09

mojmir.novak