Serilog - 如何制作自定义控制台输出格式? [英] Serilog - how to make custom console output format?

查看:152
本文介绍了Serilog - 如何制作自定义控制台输出格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

从这里:

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

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

or just this simple format:

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

推荐答案

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

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

更丰富:

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

这篇关于Serilog - 如何制作自定义控制台输出格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆