NLog.Targets.Splunk如何取消Properties外层包裹实现扁平化日志输出?
NLog.Targets.Splunk 扁平化日志输出方案
可以实现无Properties外层包裹的扁平化日志输出,常用两种实现方案如下:
方案1:使用自定义JsonLayout(推荐)
直接替换Splunk目标的默认Layout为NLog原生JsonLayout,开启flattenJson属性即可自动把所有事件属性提升到JSON根节点:
<target xsi:type="SplunkHttpEventCollector" name="splunkTarget" serverUrl="你的Splunk HEC服务地址" token="你的HEC认证令牌"> <layout xsi:type="JsonLayout" includeAllProperties="true" flattenJson="true" excludeProperties="不要输出的属性名,多个用逗号分隔"> <!-- 内置基础字段配置 --> <attribute name="Level" layout="${level}" /> <attribute name="RenderedMessage" layout="${message}" /> <!-- 自定义属性直接配置,不需要额外加contextproperty --> <attribute name="host" layout="${machinename}" /> <attribute name="threadid" layout="${threadid}" /> <attribute name="logger" layout="${logger}" /> </layout> </target>
该方案输出的日志结构完全符合要求,所有自定义事件属性都会直接作为JSON根字段存在。
方案2:保留Splunk默认序列化逻辑的配置调整
如果不想替换默认Layout,可以按如下规则调整配置:
- 将Splunk目标的
includeEventProperties设置为false - 删除所有
contextproperty节点,把需要的自定义属性直接通过attribute标签配置为根级字段
该方案也可以实现扁平化输出,适合需要保留Splunk默认内置字段的场景。
注意事项
- 同名字段的输出优先级以配置靠后的attribute为准,可按需调整配置顺序
- 不需要输出的内置字段直接删除对应的attribute配置即可
内容的提问来源于stack exchange,提问作者gunnarst
相关产品推荐
相关产品推荐

