In Serilog, how do I get properties to show like they do when using the CompactJsonFormatter with long names like when using the JsonFormatter?

huangapple go评论43阅读模式
英文:

In Serilog, how do I get properties to show like they do when using the CompactJsonFormatter with long names like when using the JsonFormatter?

问题

以下是翻译好的部分:

我有一个如下配置的Serilog记录器:

Log.Logger =
    new LoggerConfiguration()
        .ReadFrom.Configuration(configuration)
        .Enrich.FromGlobalLogContext()
        .WriteTo.Console(new JsonFormatter())
        .CreateLogger();

我的日志看起来像这样:

{
    "Timestamp": "2023-02-23T20:36:15.0931656+00:00",
    "Level": "Information",
    "MessageTemplate": "Entered the Run method",
    "Properties": {
        "x-correlation-id": "00000000-0000-0000-0000-000000000000"
    }
}

是否可以将属性,如 x-correlation-id,移到顶层?我在 CompactJsonFormatter 中看到过这种输出,但我的团队不喜欢像 @t@mt 这样的简短名称。如何使属性显示为在使用 JsonFormatter 时的长名称,就像使用 CompactJsonFormatter 时一样?

英文:

I have a Serilog logger configured as follows:

Log.Logger =
            new LoggerConfiguration()
                .ReadFrom.Configuration(configuration)
                .Enrich.FromGlobalLogContext()
                .WriteTo.Console(new JsonFormatter())
                .CreateLogger();

My logs look like this:

{
    "Timestamp": "2023-02-23T20:36:15.0931656+00:00",
    "Level": "Information",
    "MessageTemplate": "Entered the Run method",
    "Properties": {
        "x-correlation-id": "00000000-0000-0000-0000-000000000000"
    }
}

Is it possible to move the properties, like x-correlation-id, up to the top level? I've seen this kind of output in the CompactJsonFormatter but my team doesn't like the short names like @t or @mt. How do I get properties to show like they do when using the CompactJsonFormatter with long names like when using the JsonFormatter?

答案1

得分: 2

这可以通过在Serilog中使用表达式模板来实现。它允许基于表达式的日志筛选和格式化。

正如你所指出的,紧凑的Json格式化器的主要挑战是有限的自定义性,因此他们实现了ExpressionTemplate。

要使用ExpressionTemplate,我们需要添加NuGet包 - Serilog.Expressions

Expression Templates提供的一项自定义功能是允许您重命名和重新排序时间戳、级别、消息、异常和其他字段。

例如- 如果我们希望将@t重命名为"TimeStamp",@mt重命名为"Message",@l重命名为"Level",代码如下所示-

new ExpressionTemplate("{ {TimeStamp: @t,Level:@l,Message: @mt,Exception:@x , ..@p} }\n")

以下是一个比较CompactJsonFormatter和ExpressionTemplate输出的示例代码:

using Serilog;
using Serilog.Formatting.Compact;
using Serilog.Formatting.Json;
using Serilog.Templates;
using System;

namespace Alne.POT.Common
{
    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime Created { get; set; }
    }

    public class Class1
    {
        public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                .WriteTo.Console(new ExpressionTemplate("{ {TimeStamp: @t,Level:@l,Message: @mt,Exception:@x , ..@p} }\n"))
                .WriteTo.Console(new CompactJsonFormatter())
                .CreateLogger();

            var exampleUser = new User { Id = 1, Name = "Adam", Created = DateTime.Now };
            Log.Information("Created {@User} on {Created}\n", exampleUser, DateTime.Now);
            Console.WriteLine();
        }
    }
}

比较CompactJsonFormatter和Expression Template的结果,它们完全匹配,只是我们已经重命名了字段。

英文:

This can be achieved by using Expression Templates in Serilog. It allows expression based filtering and formatting of logs.

As you rightly pointed out, the major challenge with the Compact Json Formatters was limited customizability and hence they implemented ExpressionTemplate.

To use ExpressionTemplate, we need to add nuget package - Serilog.Expressions

One of the customizations provided by Expression Templates is that it allows you to rename and reorder the timestamp, level, message, exception and other fields.

For eg- We wish to rename @t to "TimeStamp", @mt to "Message", @l to "Level", the code is as simple as below-

new ExpressionTemplate("{ {TimeStamp: @t,Level:@l,Message: @mt,Exception:@x , ..@p} }\n")

Here's a sample code that compares the outputs from CompactJsonFormatter & ExpressionTemplate

using Serilog;
using Serilog.Formatting.Compact;
using Serilog.Formatting.Json;
using Serilog.Templates;
using System;
namespace Alne.POT.Common
{
    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime Created { get; set; }

    }
    public class Class1
    {
        public static void Main(string[] args)
        {

            Log.Logger = new LoggerConfiguration()
                .WriteTo.Console(new ExpressionTemplate("{ {TimeStamp: @t,Level:@l,Message: @mt,Exception:@x , ..@p} }\n"))
                .WriteTo.Console(new CompactJsonFormatter())
                .CreateLogger();

            var exampleUser = new User { Id = 1, Name = "Adam", Created = DateTime.Now };
            Log.Information("Created {@User} on {Created}\n", exampleUser, DateTime.Now);
            Console.WriteLine();
           

        }
    }

}

Comparing the results from - CompactJsonFormatter & Expression Template, it matches exactly except for the fact that we have renamed the fields.

huangapple
  • 本文由 发表于 2023年2月24日 04:46:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75550156.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定