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

如何基于自定义事件属性配置NLog的差异化日志级别?

需求实现说明

你的需求完全可以实现,但当前配置的写法存在逻辑问题,无法达到预期效果。

原配置的问题

原规则中<logger>的minlevel="Info"会直接拦截所有级别低于Info的日志(Trace、Debug),这些日志根本无法进入后续的过滤器判断,所以MyCategory的Trace级别日志不会被记录。

正确实现方案

以下提供两种可行的配置方式:

方式一:单规则内通过过滤器区分级别

<?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"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true" >

  <targets>
    <target xsi:type="File" name="logfile" fileName="myfile.log"
            layout="${longdate}  ${level}  ${event-properties:item=Category}:  ${message}  ${exception:format=tostring}" />
  </targets>

  <rules>
      <logger name="*" writeTo="logfile">
          <filters>
              <!-- 允许MyCategory的Trace及以上级别日志 -->
              <when condition="'${event-properties:item=Category}' == 'MyCategory'" action="Log" minlevel="Trace" />
              <!-- 其他业务域仅允许Info及以上级别日志 -->
              <when condition="'${event-properties:item=Category}' != 'MyCategory'" action="Log" minlevel="Info" />
              <!-- 兜底:未匹配到Category的日志按默认Info级别处理 -->
              <when action="Log" minlevel="Info" />
          </filters>
      </logger>
  </rules>
</nlog>

方式二:拆分规则并使用final属性

<?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"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true" >

  <targets>
    <target xsi:type="File" name="logfile" fileName="myfile.log"
            layout="${longdate}  ${level}  ${event-properties:item=Category}:  ${message}  ${exception:format=tostring}" />
  </targets>

  <rules>
      <!-- 优先处理MyCategory的日志,允许Trace及以上,处理后不再走后续规则 -->
      <logger name="*" writeTo="logfile" minlevel="Trace" final="true">
          <filters>
              <when condition="'${event-properties:item=Category}' == 'MyCategory'" action="Log" />
              <when action="Ignore" />
          </filters>
      </logger>
      <!-- 其他所有日志默认按Info级别记录 -->
      <logger name="*" minlevel="Info" writeTo="logfile" />
  </rules>
</nlog>

逻辑说明

  • 两种方式都先让Trace级别的日志进入规则判断,再通过过滤器区分不同业务域的日志级别。
  • 方式二通过final="true"确保匹配到MyCategory的日志不会被后续规则重复处理,逻辑更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 18:05:13