【问题标题】:NLog Structured Logging Ignore Property By NameNLog 结构化日志忽略属性按名称
【发布时间】:2021-01-22 05:41:15
【问题描述】:

所以我正在使用 NLog 和 JSON 布局目标来记录我的 .Net 应用程序及其数据,到目前为止工作正常。

但是我有一个问题,我的一些对象包含大文件数据的字节数组,这些字节数组包含在日志文件输出中,出于文件大小的原因我不想包含。

查看可用的 NLOG 教程,有一个“excludeProperties”属性,我可以将其包含在布局配置中,但我似乎无法让它真正发挥作用。

所以如果我的对象看起来像,

 public class Station : IStation
        {
       
            public int ID { get; set; }
            public string Name { get; set; }
            public string MACAddress { get; set; }
            public string ComputerName { get; set; }
    }

我在 NLog 中使用以下布局配置,

 <layout type='JsonLayout'>
                <attribute name='Time' layout='${longdate}' />
                <attribute name='Level' layout='${level:upperCase=true}'/>
                <attribute name='Call Site' layout='${callsite}'/>

                <attribute name='Data' encode='false' >
                    <layout type='JsonLayout'
                            includeAllProperties="true"
                            maxRecursionLimit="20" 
                            excludeProperties="Name"
                        >
                        <attribute name='message' layout='${message}' encode='false' />
                        <attribute name='exception' layout='${exception}' />
                    </layout>
                </attribute>
            </layout>

然后使用结构化日志调用:

 _logger.Debug("Station Details:{@0}", Station);

  

NLog 输出仍然在生成的日志中包含 Name 属性。在此示例中,它只是 name 属性,但是其他对象包括从数据库中删除的大文件数据,我想排除这些特定属性...

那么我如何专门针对 Station 对象的 Name 属性,记住“Name”属性将存在于其他对象中。

我已经尝试了以下属性,它们仍然在输出中包含 Name 属性。

 excludeProperties="_Name"
    excludeProperties="Name"
    excludeProperties="Station_Name"
    excludeProperties="IStation_Name"

在 NLog 中使用结构化日志时忽略属性的正确“语法”是什么?

【问题讨论】:

    标签: c# nlog


    【解决方案1】:

    excludeProperties-选项控制是否根据属性名称排除一个或多个LogEventInfo.Properties。它不控制从实际属性值中排除哪些对象属性。

    这将捕获Station-value 并将其与属性名称secret1 一起存储:

     _logger.Debug("Station Details:{@secret1}", Station);
    

    这将排除属性名称为secret1secret2 的任何属性值:

     excludeProperties="secret1,secret2"
    

    如果您想从属性值类型中控制要包含的对象属性,那么您可以这样做:

        NLog.LogManager.Setup().SetupSerialization(s =>
           s.RegisterObjectTransformation<Station>(station => new {
              ID = station.ID,
              MACAddress = station.MACAddress,
              ComputerName = station.ComputerName,
           })
        );
    

    另请参阅:https://github.com/NLog/NLog/wiki/How-to-use-structured-logging#transform-captured-properties

    【讨论】:

    • 完美,现在更有意义了,谢谢你的例子。
    • 例如,最好创建一个自定义属性来标记数据模型的对象属性,这样您就不需要维护第二组对象属性转换。类似于 JSON.net 的 [JsonIgnore] 属性。
    • @ShannonRoos 您可以随时考虑将默认的 NLog JsonSerializer 替换为 Json.Net - github.com/NLog/NLog/wiki/…
    猜你喜欢
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    • 2014-03-21
    相关资源
    最近更新 更多