c# - Serilog 序列化字段

标签 c# .net serilog seq seq-logging

如果我有以下类(class)

public class Customer
{
    public string Name;
}

然后在Serilog中有如下日志命令

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .WriteTo.Seq("http://localhost:5341")
    .CreateLogger();

var item = new Customer();
item.Name = "John";
Serilog.Log.Information("Customer {@item}", item);

日志只是在 Seq 中显示为

Customer {}

如果我将 Name 字段更改为一个属性,它会起作用,但我不想在这个阶段这样做。有什么解决办法吗?

最佳答案

要仅针对一种类型执行此操作(推荐),您可以使用:

.Destructure.ByTransforming<Customer>(c => new { c.Name })

如果你想包含所有类型的公共(public)字段,或者那些匹配某种条件的公共(public)字段,你可以插入一个策略来实现:

class IncludePublicFieldsPolicy : IDestructuringPolicy
{
    public bool TryDestructure(
        object value,
        ILogEventPropertyValueFactory propertyValueFactory,
        out LogEventPropertyValue result)
    {
        if (!(value is SomeBaseType))
        {
            result = null;
            return false;
        }

        var fieldsWithValues = value.GetType().GetTypeInfo().DeclaredFields
            .Where(f => f.IsPublic)
            .Select(f => new LogEventProperty(f.Name,
               propertyValueFactory.CreatePropertyValue(f.GetValue(value))));

        result = new StructureValue(fieldsWithValues);
        return true;
    }
}

该示例将其范围缩小为仅查看从 SomeBaseType 派生的对象。

您可以将其插入:

.Destructure.With<IncludePublicFieldsPolicy>()

(我认为这可能需要一些调整,但应该是一个很好的起点。)

关于c# - Serilog 序列化字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46152092/

相关文章:

.net - ClickOnce部署 "System.IO.IOException"

asp.net - web.config asp.net mvc 5 中的 serilog AppSetting

javascript - JavaScript/jQuery 中是否有类似于.NET 的 Path.Combine() 类型方法

c# - .NET:XML 文档 - CREF 标记中使用的程序集别名

c# - 使用 Reporting Services 将报告直接发送到打印机

c# - 如果我使用 Parallel.ForEach(),为什么会丢失某些文件?

c# - “Could not find a part of the path” Azure WebApp 中的文件读取操作错误

c# - 如果异步日志记录在 asp.net core 中失败,则调用一个操作

c# - 自定义 Serilog 接收器无法使用 AppSettings 工作

c# - 无法将简单的字符串列表数组绑定(bind)到 ListView