nlog彩色控制台



我正在使用nlog来记录错误。这是配置代码

<target name="console" xsi:type="AsyncWrapper" >
      <target  xsi:type="ColoredConsole"  layout="${longdate:padding=-10}${callsite:className=false:includeSourcePath=false:methodName=false} | ${message}" >
         <highlight-row condition="level >= LogLevel.Info" foregroundColor="Green" backgroundColor="NoChange"/> 
      </target>
    </target>

我在日志事件上有一个自定义属性,例如

private LogEventInfo GetLogEvent(string loggerName, LogLevel level, string message, ConsoleColor color)
        {
    var logEvent = new LogEventInfo(level, loggerName, message);
                logEvent.Properties["color"] = color;// color= any console color
}

这设置了"彩色"属性。(在这里说"红色")

我试图在目标中使用此"颜色"属性,例如

 <highlight-row condition="equals('${color}','Red')" foregroundColor="Red" backgroundColor="NoChange"/> 

我尝试了这项工作,我尝试了

<highlight-row condition="equals('${event-context:item=color}','Red')" foregroundColor="Red" backgroundColor="NoChange"/> 

但没有运气。

我错过了什么,还是有更好的方法来做到这一点?在这种情况下,我们可以使用布局渲染器吗?如果是,我们如何实现?

首先,由于您在LogEventInfo.Properties中存储值,因此您应该使用第二个配置示例,该示例从event-context获取值。

我尚未使用ColoredConsoleTarget,所以请以此为建议,而不是我知道的事实会起作用。

我怀疑NLOG Condition对象对ConsoleOutputColor枚举不了解。因此,当您将ConsoleOutputColor枚举值存储在LogEventInfo.Properties中时,Condition不知道'Red'(在这种情况下)是指ConsoleOutputColor.Red。我有两个建议:

第一个选项:将ConsoleOutputColor的字符串值存储在LogEventInfo.Properties中。使用ToColor可能就足够了。这样的东西:

var logEvent = new LogEventInfo(level, loggerName, message);
logEvent.Properties["color"] = color.ToString();

然后,在您的Condition中,您应该能够与ConsoleOutputColor字符串值进行比较(如果您按照我的建议存储颜色名称字符串,则配置中的内容可能正确)。

如果那不起作用,您可以尝试...

第二个选项:将ConsoleOutputColor值存储在LogEventInfo.Properties中,就像您现在所做的那样,但在配置文件中更改条件,以将"颜色"从事件 - 偏置与ConsoleOutputColor值的数字值进行比较。这样的事情(我没有尝试过,所以我不确定它是正确的):

<highlight-row condition="equals('${event-context:item=color}','12')" foregroundColor="Red" backgroundColor="NoChange"/>

(在ConsoleOutputColor枚举中,Red12)。

最新更新