首页 文章

使用nlog替换布局渲染器,替换似乎是两次而不是一次

提问于
浏览
0

我正在尝试使用NLog替换布局渲染器(https://github.com/NLog/NLog/wiki/Replace-Layout-Renderer) . 我希望用它来截断过长的消息 . 它似乎能够这样做,但更换发生两次而不是一次 .

在我的nlog.config中,我使用以下内容:

<variable name="replaced_message" value="${replace:searchFor=.*:replaceWith=Replaced:regex=true:inner=${message}}"/>

<target name="filelog" xsi:type="File" fileName="${basedir}/../logs/webapp/${shortdate}.log"
    layout="${date:format=yyyy-MM-dd HH\:mm\:ss.fff}|${level:uppercase=true}|${machinename}|T:${threadid}|${logger}|${replaced_message}"/>

我得到的日志条目如下:

2015-03-04 13:41:14.337|INFO|T:11|ReplacedReplaced

有没有人知道为什么消息是“ReplaceReplaced”而不是“替换”?

谢谢!

1 回答

  • 2

    原来这个问题与Nlog无关 . 这只是正则表达式的问题 - 与此处发现的问题相同:

    Why does my Regex.Replace string contain the replacement value twice?

    实际上有2个匹配正则表达式“ . *” .

    *表示匹配零个或多个字符,因此有2个匹配 - 空字符串和文本 .

    将模式更改为“ . ”而不是“ . *”可以解决问题 . “ . ”表示匹配一个或多个字符,因此它不再匹配空字符串 .

    这有点像我的脑袋一样混乱,但看起来确实像那样 .

    顺便说一下,如果有人对我的原始计划做同样的事情,要将Nlog消息截断为500个字符,可以使用nlog.config中的以下内容完成:

    <variable name="truncated_message" value="${replace:replaceWith=...TRUNCATED:regex=true:inner=${message}:searchFor=(?&lt;\=.\{500\}).+}"/>
    
    <target name="filelog" xsi:type="File" fileName="${basedir}/../logs/jobs/${shortdate}.log" layout="${date:format=yyyy-MM-dd HH\:mm\:ss.fff}|${level:uppercase=true}|${truncated_message}"/>
    

相关问题