使用Serilog时如何在输出消息中获取丰富的属性 [英] How to get an enriched property in the output message when using Serilog

查看:126
本文介绍了使用Serilog时如何在输出消息中获取丰富的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Serilog将丰富的属性输出到呈现的消息中:

I'm trying to output an enriched property into the rendered message using Serilog:

private static Tester GetTester()
{
    return new Tester {Count = 7, Name = "Redmond"};
}

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Verbose()
    .Enrich.WithProperty("Site", "Dan Local")
    .WriteTo
    .ColoredConsole()
    .CreateLogger();

var tester = GetTester();

Log.Verbose("{Site} - This is verbose {@tester}", tester);
Log.Verbose("This is verbose {@tester} - {Site}", tester);

第一个log语句输出:

The first log statement outputs:

2014-08-19 10:02:25 [Verbose] "SeriLogTest.Tester" - This is verbose {@tester}

第二个log语句输出:

The second log statement outputs:

2014-08-19 10:02:25 [Verbose] This is verbose Tester { Count: 7, Name: "Redmond" } - "Dan Local"

我希望他们两个都以消息模板定义的不同顺序输出相同的信息.但是如您所见,如果您不将riched属性放在最后,它将被提供的对象接管并记录下来,而第二个template属性将被忽略.有办法吗?

I would expect them both to output the same information, just in a different order as defined by the message template. But as you can see, if you don't put the enriched property last, it is taken over by the provided object to be logged and the second template property is ignored. Is there a way to do this?

推荐答案

输出模板是实现此目的的方法,即:

Output templates are the way to achieve this, i.e.:

    .WriteTo.ColoredConsole(
      outputTemplate: "{Timestamp:HH:mm} [{Level}] {Site}: {Message}{NewLine}{Exception}")

这将打印Site属性的值以及每条消息;例如:

This will print the value of the Site property along with every message; e.g.:

Log.Information("Hello");

打印:

19:40 [Information] Dan Local: Hello

这篇关于使用Serilog时如何在输出消息中获取丰富的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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