serilog 不记录整个 dto 对象

serilog does not log the entire dto object

我们有以下 serilog 代码,集合和简单字符串正在按预期编写,但是当我们尝试记录一个对象时,serilog 输出以下评分器而不是该对象,是否还有其他设置需要完成记录元数据对象的所有属性?

[16:40:59 INF] 处理 {"$type": "Metadata"}

[16:40:59 INF] 处理程序+元数据

注意:我们在控制台应用程序中使用它

using System;
using System.Collections.Generic;
using Serilog;

class Program
{
    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Information()
            .WriteTo.Console()
            .WriteTo.File("log.txt",
                rollingInterval: RollingInterval.Day,
                rollOnFileSizeLimit: true)
            .CreateLogger();

        Metadata metadata =new Metadata();
        metadata.Name = "hello";
        
        var fruit = new[] { "Apple", "Pear", "Orange" }; 

        Log.Information("In my bowl I have {Fruit}", fruit);
        Log.Information("Processing {@HubTableMetadata}", metadata);
        Log.Information("Processing {HubTableMetadata}", metadata);
        Log.CloseAndFlush();

        Console.Read();
    }

    public class Metadata
    {
        public string Name;
        public string[] Tags;
        public List<string> keys;
    }
}

Serilog 解构了 properties,但是你的 Metadata class 只定义了 fields.

要获得您想要的行为,请更新您的 Metadata class 以使用属性:

public class Metadata
{
    public string Name { get; set; }
    public string[] Tags  { get; set; }
    public List<string> Keys { get; set; }
}

如果要自定义输出结构化数据,可以看看不同的Destructurama projects

您可能也有兴趣阅读此post“Using attributes to control destructuring in Serilog”。