5

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

但没有运气。

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

4

1 回答 1

2

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

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

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

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

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

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

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

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

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

(在ConsoleOutputColor枚举中,Red12)。

于 2012-10-29T14:41:00.737 回答