You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NLog无法将${all-event-properties}写入File目标的问题求助

问题

使用NLog 5.1.4版本,配置如下(已简化):

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true">
    <extensions>
        <add assembly="NLog.Targets.ElasticSearch"/>
    </extensions>
    <variable name="projectName" value="WebApi" />
    <variable name="environment" value="${appsetting:item=Environment}"/>
    <targets async="true">
        <target name="file" xsi:type="File" fileName="C:\Logs\${projectName}\file.log"
                layout="${date} | ${level} | ${message} | ${all-event-properties}" />
        <target name="elastic" xsi:type="BufferingWrapper" flushTimeout="5000">
            <target xsi:type="ElasticSearch"
                    includeAllProperties="true"
                    index="${environment}-${lowercase:${projectName}}-${date:format=yyyy.MM.dd}"
                    uri="http://localhost:9200"
                    layout="${message}">
            </target>
        </target>
    </targets>
    <rules>
    <logger name="*" minlevel="Info" writeTo="file,elastic"/>
    </rules>
</nlog>

通过Fluent API写入的日志属性在Elastic中能正常显示,但在File目标的日志文件里看不到,分隔符后只有空格。单独打印属性也得到相同结果,NLog内部日志无错误提示,请问问题出在哪?

解决方法

问题出在${all-event-properties}的默认行为上——它默认不会输出任何内容,除非指定格式化模板。

修改File目标的layout,给${all-event-properties}添加格式参数即可:

layout="${date} | ${level} | ${message} | ${all-event-properties:format=[${key}]=${value}:separator=, }"

上述配置会让属性以[Key]=Value, [Key2]=Value2的格式显示在日志中。

如果只需要输出特定属性,也可以单独指定:

layout="${date} | ${level} | ${message} | UserId=${event-properties:UserId}, OrderId=${event-properties:OrderId}"

这种方式适合需要精准控制输出内容的场景。

内容的提问来源于stack exchange,提问作者Artem Grunin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 00:48:18