NLog日志输出重定向异常:启用When过滤器后logSource文件未生成
NLog过滤器导致logSource文件无法生成的解决办法
问题根源
你注释掉的when过滤器存在两个关键问题:
- 逻辑颠倒:
not isset('${event-properties:logSource}')的作用是忽略存在logSource属性的消息,和你想要的“仅保留有logSource的消息”完全相反; - 语法与边界处理缺失:NLog条件表达式中
isset的用法不符合规范,且未处理logSource属性存在但为空的情况,会导致生成无效文件名,进而无法创建日志文件。
修正步骤
1. 修复过滤器条件
将过滤器改为忽略logSource不存在或为空的消息,正确写法如下:
<when condition="empty('${event-properties:logSource}')" action="Ignore" />
如果要同时严格检查属性是否存在,也可以写成:
<when condition="not isset('${event-properties:logSource}') or empty('${event-properties:logSource}')" action="Ignore" />
2. 完善日志文件名配置
给fileInfoSource的fileName添加默认值,避免属性为空时生成无效文件名:
fileName="${event-properties:logSource:whenEmpty=unknown}.log"
完整修正后的NLog.config
<?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"> <targets> <target xsi:type="File" name="fileInfo" fileName="all.log" layout="${longdate}|${level}|${event-properties:logSource}" /> <target xsi:type="File" name="fileInfoSource" fileName="${event-properties:logSource:whenEmpty=unknown}.log" layout="${longdate}|${level}|${event-properties:logSource}" /> </targets> <rules> <logger name="*" minlevel="Info" writeTo="fileInfo"/> <logger name="*" minlevel="Info" writeTo="fileInfoSource"> <filters> <when condition="empty('${event-properties:logSource}')" action="Ignore" /> </filters> </logger> </rules> </nlog>
验证结果
运行你的代码后:
- 带有
logSource="Program"的日志会同时写入all.log和Program.log; - 未设置
logSource的日志只会出现在all.log中,不会生成额外的日志文件。
内容的提问来源于stack exchange,提问作者theateist
相关产品推荐
相关产品推荐

