NLOG - 生成头章节一个日志文件 [英] Nlog - Generating Header Section for a log file

查看:169
本文介绍了NLOG - 生成头章节一个日志文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近刚刚进入与NLOG试验,它发生,我认为,我想能够添加标题信息前一个日志文件,如:

Just recently got into experimenting with NLog, and it occurs to me that I would like to be able to add header information to the top a log file such as:

可执行文件的名字
文件版本
发布日期
Windows用户ID
等...

Executable name File version Release Date Windows User ID etc...

在一些搜索我一直未能找到这表明这种类型的功能在现有的在线文档或代码论坛什么。这可能吗?我一直此前列入这一类的日志文件的信息,并发现它在过去许多occsions有用的,在客户现场采购生产问题的信息的时候。诚然,此功能是定制的解决方案,而不是基于任何当前的.NET日志框架中。

After some searching I have been unable to find anything in the existing on-line documentation or code forums which indicates this type of functionality. Is this possible? I have always previously included this sort of information in log files, and have found it useful on numerous occsions in the past, when sourcing information on production issues at customer sites. Admittedly, this functionality was custom built for the solutions and not based on any of the current .NET logging frameworks.

推荐答案

我米不知道的方式做到这一点很容易。说了这么多,大家给的例子是可用的(或相当相当容易地可用一些自定义代码)被添加到每个日志消息。也就是说,每一个登录的消息可以被标记为可执行文件名,文件版本,发布日期,Windows用户ID,通过布局和LayoutRenderers等。

I'm not aware of a way to do that very easily. Having said that, all of the examples you give are available (or pretty fairly easily available with some custom code) to be added to each log message. That is, each logged message can be tagged with executable name, file version, release date, windows user id, etc via the Layout and LayoutRenderers.

这显然是不同刚刚创建的日志文件的顶部标题,所以它可能不会对你有用。

This is obviously not the same as just creating a header at the top of the log file, so it might not be useful to you.

在另一方面,你可以使用中提到的技术在这个岗位帕特的答案多个布局与渲染相同的目标联系起来。你可以定义布局包含您在您的标题的栏目,并在FilteringWrapper过滤器设置为仅适用于该布局在会话的第一个消息(或者你可以使用它添加到输出文件中的一些其他技术只有一次)。

On the other hand, you could use a technique mentioned in Pat's answer in this post to associate multiple layout renderers with the same target. You could define a layout that contains the fields that you want in your header and set the filter in the FilteringWrapper to only apply that layout for the first message of a session (or you might use some other technique that it is added to the output file only once).

用他NLog.config文件,这里是您可能实现你想要的一种方式。请注意,我没有尝试这样做,所以我不知道如果这个配置文件是有效的,如果是,它是否会产生你想要的结果。

Using his NLog.config file, here is one way that you might achieve what you want. Note that I have not tried this, so I don't know if this config file is valid or, if it is, if it will generate the results that you want.

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.mono2.xsd" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      autoReload="true" 
      internalLogLevel="Warn" 
      internalLogFile="nlog log.log" 
      > 
    <variable name="HeaderLayout" value="${processname} ${gdc:item=version} ${gdc:item=releasedate} ${windows-identity}" /> 
    <variable name="NormalLayout" value="${longdate} ${logger} ${level} ${message} /> 

    <targets async="true"> 
        <target name="file" xsi:type="File" fileName="log.log" 
                layout="${NormalLayout}"> 
        </target> 

        <target name="fileHeader" xsi:type="File" fileName="log.log" 
                layout="${HeaderLayout}"> 
        </target>      
    </targets> 

    <rules> 
        <logger name="HeaderLogger" minlevel="Trace" writeTo="fileHeader" final="true" />           
        <logger name="*" minlevel="Trace" writeTo="file" /> 
    </rules> 

</nlog> 

在你的代码,你的启动逻辑可能是这样的:

In your code, your startup logic might look like this:

public void Main()
{
  AddHeaderToLogFile();
}

public void AddHeaderToLogFile()
{
  Logger headerlogger = LogManager.GetLogger("HeaderLogger");

  //Use GlobalDiagnosticContext in 2.0, GDC in pre-2.0
  GlobalDiagnosticContext["releasedate"] = GetReleaseDate();    
  GlobalDiagnosticContext["version"] = GetFileVersion();     
  GlobalDiagnosticContext["someotherproperty"] = GetSomeOtherProperty();

  headerlogger.Info("message doesn't matter since it is not specified in the layout");

  //Log file should now have the header as defined by the HeaderLayout

  //You could remove the global properties now if you are not going to log them in any
  //more messages.
}



这里的想法是,你会把文件版本,发布日期等在GDC程序启动时。登录的消息与HeaderLogger记录器。这个消息将被写入到使用HeaderLayout自HeaderLogger与其与HeaderLayout相关联的FileHeader里目标相关联的日志文件。在头布局定义的字段被写入到日志文件中。子日志消息,因为它们不会用HeaderLogger,将使用根(*)的布局。他们会去,因为同一个文件中的文件和FileHeader里的目标最终指向相同的文件名。

The idea here is that you would put the file version, release date, etc in the GDC when the program starts. Log a message with the "HeaderLogger" logger. This message would be written to the log file using the "HeaderLayout" since the "HeaderLogger" is associated with the "fileHeader" target which is associated with the "HeaderLayout". The fields defined in the header layout are written to the log file. Subsequence log messages, since they will not use the "HeaderLogger", will use the "root" (*) layout. They will go to the same file since both the "file" and "fileHeader" targets ultimately point to the same filename.

在我开始打字这个反应我是不是相信你可以做到多么容易添加头部日志文件。已经输入的那样,我认为它实际上可能是很容易!

Before I started typing this response I wasn't sure how easily you could accomplish adding a header to your log file. Having typed this, I think that it might actually be pretty easy!

祝你好运!

这样的事情可能会努力改变基于等级的布局。在第一部分我已经定义几个变量,其中每一个定义了一个布局。在下一节我已经定义其中每个使用相同的文件的几个目标,但被过滤以仅允许特定水平的消息被写入。在最后一节,我定义一个规则,将所有消息(因此*记录器名称)发送到所有目标。由于每个目标逐级筛选,跟踪目标将只写跟踪的消息等,所以,跟踪的消息将使用跟踪布局中写道,调试的消息将使用调试写布局等。由于所有目标最终写入同一个文件,所有的消息都会在同一文件中结束。我没有试过,但我认为,它可能会正常工作

Something like this might work to change the layout based on level. In the first section I have defined several variables, each of which defines a layout. In the next section I have defined several targets each of which uses the same file, but is filtered to only allow messages of a specific level to be written. In the final section I define a single rule that will send all messages (hence the "*" logger name) to all targets. Since each target is filtered by level, the "trace" target will write only "trace" messages etc. So, "trace" messages will be written using the "trace" layout, "debug" messages will be written using the "debug" layout, etc. Since all targets ultimately write to the same file, all messages will end up in the same file. I haven't tried this, but I think that it will probably work.

<variable name="TraceLayout" value="THIS IS A TRACE: ${longdate} ${level:upperCase=true} ${message}" /> 
<variable name="DebugLayout" value="THIS IS A DEBUG: ${longdate} ${level:upperCase=true} ${message}" /> 
<variable name="InfoLayout" value="THIS IS AN INFO: ${longdate} ${level:upperCase=true} ${message}" /> 


<targets async="true"> 
    <target name="fileAsTrace" xsi:type="FilteringWrapper" condition="level==LogLevel.Trace"> 
        <target xsi:type="File" fileName="log.log" layout="${TraceLayout}" /> 
    </target> 
    <target name="fileAsDebug" xsi:type="FilteringWrapper" condition="level==LogLevel.Debug"> 
        <target xsi:type="File" fileName="log.log" layout="${DebugLayout}" /> 
    </target> 
    <target name="fileAsInfo" xsi:type="FilteringWrapper" condition="level==LogLevel.Info"> 
        <target xsi:type="File" fileName="log.log" layout="${InfoLayout}" /> 
    </target>  
</targets> 

<rules> 
    <logger name="*" minlevel="Trace" writeTo="fileAsTrace, fileAsDebug, fileAsInfo" /> 
</rules> 



(请注意,我只这里包括3个等级)。

(Note that I have only included 3 levels here).

已经展示了如何(如果它的工作原理,反正)申请根据级别不同的布局,这似乎是某种不寻常的用例。我并不是说这是一个好主意还是一个坏主意,但我不能说,我真的看到了这一点做的非常多。根据你想究竟是如何最终输出看,我已经表明你可能会或可能不会实现这一目标的最佳途径。也许你可以张贴你希望你的输出看一些例子。

Having shown how (if it works, anyway) to apply a different layout based on level, this seems like sort of an unusual use case. I'm not saying that it is a good idea or a bad idea, but I can't say that I have really seen this done very much. Depending on exactly how you want your final output to look, what I have shown you may or may not be the best way to achieve it. Maybe you could post some examples of how you want your output to look.

您也可以考虑接受我原来的答案,然后又做了新的问题,如何改变每个输出布局水平,使我们能够在水平/布局的问题,重点问题的讨论。它是由你如果还算有用与否

You might also consider accepting my original answer and then making a new question about varying the output layout per level so that we can focus the discussion in that question on the level/layout issue. It is up to you if that seems useful or not.

本作品:

  <variable name="TraceLayout" value="This is a TRACE - ${longdate} | ${logger} | ${level} | ${message}"/>
  <variable name="DebugLayout" value="This is a DEBUG - ${longdate} | ${logger} | ${level} | ${message}"/>
  <variable name="InfoLayout" value="This is an INFO - ${longdate} | ${logger} | ${level} | ${message}"/>
  <variable name="WarnLayout" value="This is a WARN - ${longdate} | ${logger} | ${level} | ${message}"/>
  <variable name="ErrorLayout" value="This is an ERROR - ${longdate} | ${logger} | ${level} | ${message}"/>
  <variable name="FatalLayout" value="This is a FATAL - ${longdate} | ${logger} | ${level} | ${message}"/>
  <targets>
    <target name="fileAsTrace" xsi:type="FilteringWrapper" condition="level==LogLevel.Trace">
      <target xsi:type="File" fileName="xxx.log" layout="${TraceLayout}" />
    </target>
    <target name="fileAsDebug" xsi:type="FilteringWrapper" condition="level==LogLevel.Debug">
      <target xsi:type="File" fileName="xxx.log" layout="${DebugLayout}" />
    </target>
    <target name="fileAsInfo" xsi:type="FilteringWrapper" condition="level==LogLevel.Info">
      <target xsi:type="File" fileName="xxx.log" layout="${InfoLayout}" />
    </target>
    <target name="fileAsWarn" xsi:type="FilteringWrapper" condition="level==LogLevel.Warn">
      <target xsi:type="File" fileName="xxx.log" layout="${WarnLayout}" />
    </target>
    <target name="fileAsError" xsi:type="FilteringWrapper" condition="level==LogLevel.Error">
      <target xsi:type="File" fileName="xxx.log" layout="${ErrorLayout}" />
    </target>
    <target name="fileAsFatal" xsi:type="FilteringWrapper" condition="level==LogLevel.Fatal">
      <target xsi:type="File" fileName="xxx.log" layout="${FatalLayout}" />
    </target>
  </targets>


    <rules>
      <logger name="*" minlevel="Trace" writeTo="fileAsTrace,fileAsDebug,fileAsInfo,fileAsWarn,fileAsError,fileAsFatal" />
      <logger name="*" minlevel="Info" writeTo="dbg" />
    </rules>



我已经设置了每个日志记录级别一个布局,在描述的开头添加一个字符串该消息的水平(这是要表明,不同的格式用于每个级别)。每个布局与该滤波器基于消息的水平,并指示通过过滤器在输出文件中记录的任何消息FilteringWrapper有关。每个FilteringWrapper披着同一个输出文件,因此,所有的日志信息将被记录到同一文件

I have set up one Layout for each logging level, adding a literal string at the beginning that describes the level of the message (this is to show that a different format is used for each level). Each Layout is associated with a FilteringWrapper that filters based on the level of the message and directs any messages that pass the filter to be logged in the output file. Each FilteringWrapper is wrapping the same output file, so all log messages will be logged to the same file.

下面是我用于测试的一段代码:

Here is a section of code that I used for testing:

  logger.Trace("Trace msg");
  logger.Debug("Debug msg");
  logger.Info("Info msg");
  logger.Warn("Warn msg");
  logger.Error("Error msg");
  logger.Fatal("Fatal msg");

和这里的输出看起来是这样的:

And here is what the output looks like:

This is a TRACE - 2010-11-22 13:20:00.4131 | NLogTest.Form1 | Trace | Trace msg
This is a DEBUG - 2010-11-22 13:20:00.4131 | NLogTest.Form1 | Debug | Debug msg
This is an INFO - 2010-11-22 13:20:00.4131 | NLogTest.Form1 | Info | Info msg
This is a WARN - 2010-11-22 13:20:00.4131 | NLogTest.Form1 | Warn | Warn msg
This is an ERROR - 2010-11-22 13:20:00.4131 | NLogTest.Form1 | Error | Error msg
This is a FATAL - 2010-11-22 13:20:00.4131 | NLogTest.Form1 | Fatal | Fatal msg



显然,在我以前的配置信息,问题之间的空间的 的writeTo值。我猜NLOG对这个敏感。我有这样的事情的writeTo = blah1,blah2,blah3。当我改变了以的writeTo = blah1,blah2,blah3错误就走开了。
祝你好运!

Apparently the problem in my earlier config information was the space between the "writeTo" values. I guess NLog is sensitive to this. I had something like "writeTo=blah1, blah2, blah3". When I changed that to "writeTo=blah1,blah2,blah3" the error went away. Good luck!

这篇关于NLOG - 生成头章节一个日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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