NLog彩色控制台

7
我正在使用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"/> 

但是没有运气。

我是否遗漏了什么,或者有更好的方法来解决这个问题?我们可以在这种情况下使用Layout渲染器吗?如果可以,如何实现?

1个回答

3

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

我没有使用过ColoredConsoleTarget,所以把这个当作建议而非确切可行的方法。

我怀疑NLog Condition对象不知道ConsoleOutputColor枚举。 因此,当您将ConsoleOutputColor枚举值存储在LogEventInfo.Properties中时,Condition不知道条件中的'Red'是指ConsoleOutputColor.Red。 我有两个建议:

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

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

接下来,在你的Condition中,你应该可以针对ConsoleOutputColor字符串值进行比较(如果你按照我建议的将颜色名称字符串存储,则你配置文件中的内容可能是正确的)。

如果这样不起作用,你可以尝试以下方法...

第二个选项:像你现在做的那样,将ConsoleOutputColor的值存储在LogEventInfo.Properties中,但是更改配置文件中的条件,将事件上下文中的“color”与ConsoleOutputColor值的数字值进行比较。 大概是这样(我没有尝试过,所以我不确定它是否正确):

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

(在ConsoleOutputColor枚举中,Red表示为12)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接