NLog 彩色控制台

Gok*_*kul 7 asp.net console nlog c#-4.0

我正在使用 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>
Run Code Online (Sandbox Code Playgroud)

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

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
}
Run Code Online (Sandbox Code Playgroud)

这设置了“颜色”属性。(这里说“红色”)

我试图在目标中使用这个“颜色”属性,例如

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

这个工作,我尝试过

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

但没有运气。

我错过了什么或者有更好的方法吗?在这种情况下我们可以使用布局渲染器吗?如果是,我们如何实施?

wag*_*ghe 3

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

我没有使用过ColoredConsoleTarget,所以将此作为一个建议,而不是我知道的事实会起作用。

我怀疑 NLogCondition对象不知道枚举ConsoleOutputColor。因此,当您ConsoleOutputColor在 中存储枚举值时LogEventInfo.PropertiesCondition不知道'Red'(在条件中)引用ConsoleOutputColor.Red。我有两个建议:

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

var logEvent = new LogEventInfo(level, loggerName, message);
logEvent.Properties["color"] = color.ToString();
Run Code Online (Sandbox Code Playgroud)

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

如果这不起作用,你可以尝试...

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

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

(在ConsoleOutputColor枚举中,Red12)。