如何在NLog中将不同的布局应用于同一目标? [英] How to apply different layouts to the same target in NLog?

查看:74
本文介绍了如何在NLog中将不同的布局应用于同一目标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

NLog允许我使用 SplitGroup 将我的消息记录到多个目标。我想使用此功能一次将每条消息记录到常见的,特定于用户的和特定于日期的日志

NLog allows me to use SplitGroup to log my messages to several targets. I'd like to use this feature to log each message to a common, user-specific and date-specific logs at once:

<variable name="commonLog" value="${logDir}\Common.log" />
<variable name="username" value="${identity:fSNormalize=true:authType=false:isAuthenticated=false}" />
<variable name="userLog" value="${logDir}\ByUser\${username}.log" />
<variable name="dateLog" value="${logDir}\ByDate\${shortdate}.log" />

<target name="logFiles" xsi:type="SplitGroup">
  <target xsi:type="File" fileName="${commonLog}" layout="${myLayout}" />
  <target xsi:type="File" fileName="${userLog}" layout="${myLayout}" />
  <target xsi:type="File" fileName="${dateLog}" layout="${myLayout}" />
</target>

这很棒,但是我也想针对不同的严重程度使用不同的布局。例如, errorLayout 将包含异常信息并插入 [!] 标记,以便稍后在日志查看器中突出显示错误,例如 BareTail

This is great, but I also want to use different layouts for different levels of severity. For example, errorLayout would include exception information and insert [!] marker so I could later highlight errors in log viewers like BareTail:

<variable name="stamp" value="${date} ${username} ${logger}" />

<variable name="debugLayout" value="${stamp} ... ${message}" />
<variable name="infoLayout" value="${stamp} [i] ${message}" /> 
<variable name="warnLayout" value="${stamp} [!] ${message}" />
<variable name="errorLayout"
   value="${warnLayout}${newline}${pad:padding=10:inner=${exception:format=ToString}}" />

<!-- logFiles target -->

<rules>
  <logger name="*" level="Debug" writeTo="logFiles" layout="debugLayout"  />
  <logger name="*" level="Info" writeTo="logFiles" layout="infoLayout" />
  <logger name="*" level="Warn" writeTo="logFiles" layout="warnLayout" />
  <logger name="*" level="Error" writeTo="logFiles" layout="errorLayout" />
</rules>

此代码假定 Error 始终带有异常和警告并没有,但这不是重点。

This code assumes Errors always come with exceptions and Warnings don't but that's not the point.

问题是此配置是错误。由于 logger 没有 layout 属性,因此无法使用。它仅针对 target 定义。

The problem is this configuration is wrong. It won't work because logger does not have layout attribute. It's defined for target only.

所使用的布局必须由目标自己声明,但我

现在,我不得不复制粘贴相同的配置代码四次,只有四个同一组文件的不同布局

For now, I had to copy-paste the same configuration code four times just to have four different layouts for same set of files:

<targets>
  <target name="logFilesDebug" xsi:type="SplitGroup">
    <target xsi:type="File" fileName="${commonLog}" layout="${debugLayout}" />
    <target xsi:type="File" fileName="${userLog}" layout="${debugLayout}" />
    <target xsi:type="File" fileName="${dateLog}" layout="${debugLayout}" />
  </target>

  <target name="logFilesInfo" xsi:type="SplitGroup">
    <target xsi:type="File" fileName="${commonLog}" layout="${infoLayout}" />
    <target xsi:type="File" fileName="${userLog}" layout="${infoLayout}" />
    <target xsi:type="File" fileName="${dateLog}" layout="${infoLayout}" />
  </target>

  <target name="logFilesWarn" xsi:type="SplitGroup">
    <target xsi:type="File" fileName="${commonLog}" layout="${warnLayout}" />
    <target xsi:type="File" fileName="${userLog}" layout="${warnLayout}" />
    <target xsi:type="File" fileName="${dateLog}" layout="${warnLayout}" />
  </target>

  <target name="logFilesError" xsi:type="SplitGroup">
    <target xsi:type="File" fileName="${commonLog}" layout="${errorLayout}" />
    <target xsi:type="File" fileName="${userLog}" layout="${errorLayout}" />
    <target xsi:type="File" fileName="${dateLog}" layout="${errorLayout}" />
  </target>
</targets>

<rules>
  <logger name="*" level="Debug" writeTo="logFilesDebug"  />
  <logger name="*" level="Info" writeTo="logFilesInfo" />
  <logger name="*" level="Warn" writeTo="logFilesWarn" />
  <logger name="*" level="Error" writeTo="logFilesError" />
</rules>

这只是伤了我的眼睛。

还有什么更好的方法吗?这样做并避免重复?

This just hurts my eyes.
Is there any better way to do this and avoid duplication?

推荐答案

我不确定,但我认为您可能被卡住了与重复。您希望在同一文件上使用4种不同的布局,并且希望3种不同的文件。一个目标需要一个布局。因此,如果只想登录到1个文件,则仍然必须定义4个目标,每个目标都指向同一文件,并且每个目标都有自己的布局。我认为NLog没有更方便的方法将多个布局与目标关联,然后根据日志消息的内容选择一个布局。

I'm not sure, but I think that you are probably stuck with the duplication. You want 4 different layouts to be used on the same file and you want 3 different files. One target requires one Layout. So, if you only wanted to log to 1 file, you would still have to define 4 Targets, each pointing to the same file and each with its own Layout. I don't think that NLog has a more convenient way to associate multiple Layouts with a Target and then choosing one Layout based on the content of the logging message.

正是您想要使用格式实现的功能,您可以通过编写自定义LayoutRenderer来减少重复。在您的示例中,您显示了Debug布局中具有 ...,Info具有[i],Warn具有[!],Error具有Warn +异常。您可以编写一个LayoutRenderer来添加特殊标记,具体取决于消息的级别。这样,您可以将调试,信息和警告全部滚动为一个布局,而错误将保留其自己的布局。

Depending on exactly what you want to achieve with your formats, you might be able to reduce the duplication somewhat by writing a custom LayoutRenderer. In your example, you show that the Debug layout has "..." in it, Info has [i], Warn has [!], and Error has Warn + exception. You could write a LayoutRenderer that adds the special marker, depending on what the level of the message is. That way, you would roll Debug, Info, and Warn all into one Layout and Error would retain its own Layout.

例如:

自定义LayoutRenderer的操作类似(基于NLog 1.0刷新,而不是2.0):

Something like this for a custom LayoutRenderer (based on NLog 1.0 refresh, not 2.0):

  [LayoutRenderer("LevelMarkerLayoutRenderer")]   
  class LevelMarkerLayoutRenderer : LayoutRenderer   
  {     
    int estimatedSize = 3;      
    protected override void Append(StringBuilder builder, LogEventInfo logEvent)
    {       
      string marker;
      switch (logEvent.Level)
      {
        case Debug:
          marker = "...";
          break;
        case Info:
          marker = "[i]";
          break;
        case Warn:
          marker = "[!]";
          break;
        case Error:
          marker = "[!]";
          break;
        case Fatal:
          marker = "[!]";
          break;
        default:
          marker = "?";
      }

      builder.Append(marker);     
    }      

    protected override int GetEstimatedBufferSize(LogEventInfo logEvent)     
    {       
      return estimatedSize;     
    }
  } 

现在,您可以配置两种布局:正常,

Now you could configure two Layouts: "normal", and "error".

类似的东西

<variable name="stamp" value="${date} ${username} ${logger}" />

<variable name="normal" value="${stamp} ${LevelMarkerLayoutRenderer} ${message}" />
<variable name="error"
   value="${warnLayout}${newline}${pad:padding=10:inner=${exception:format=ToString}}" />

您甚至可以创建一个自定义LayoutRenderer来处理异常。如果没有例外,请勿输出任何内容。如果出现异常,请合并换行符,填充和异常字符串。

You could probably even create a custom LayoutRenderer to handle exceptions. If no exception, don't output anything. If exception, concatentate newline, padding, and the exception string.

如果您有一个条件式异常布局渲染器,则可能只有一个布局看起来像

If you had a "conditional" exception layout renderer, then you could have just one layout that might look like this:

<variable name="normal" value="${stamp} ${LevelMarkerLayoutRenderer} ${message} ${ConditionalExceptionLayoutRenderer}" />

在大多数情况下,ConditionalExceptionLayoutRenderer会产生null,因为不会出现异常。

Most of the time, ConditionalExceptionLayoutRenderer would yield null because there would not be an exception.

希望这会有所帮助。

这篇关于如何在NLog中将不同的布局应用于同一目标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆