在NLog中添加方法名称

时间:2014-02-22 03:04:48

标签: c# nlog

我正在使用NLog并遵循建议的模式,在每个类上都有一个日志声明,以便能够跟踪写入日志的类/方法。我发现这对于每次写日志都有一点顶级“堆栈跟踪”非常有用。

我的代码看起来像这样:

class SomeClass {

  private static readonly Logger logger = LogManager.GetCurrentClassLogger();
     void DoStuff()   {
      logger.Debug("stuff");   }   

}

我最近要求我的单个项目写入3个单独的日志文件,为此,我添加了多个记录器和目标,如下所示:https://stackoverflow.com/a/21711838/191206

但是,现在在我的日志文件中,我丢失了类级名称。它现在只写我在NLog.config中指定的日志名称。我考虑过简单地通过调用

添加方法名称
System.Reflection.MethodBase.GetCurrentMethod(); // use Name property

或在反射中使用其他内容,例如this

然而,我想知道NLog是否有内置的东西我错过了? Debug()方法我只看到写字符串的能力,参数&可选格式..

这是内置到NLog吗?

1 个答案:

答案 0 :(得分:40)

您可以使用built in layout renderer called ${callsite}在日志条目中包含呼叫站点信息(类名,方法名和源信息):

<targets>
  <target
    name="task1File"
    xsi:type="File"
    layout="${callsite} - ${message}"
    fileName="${basedir}../Data/debugLog1.txt"
    archiveAboveSize ="5000000"
    maxArchiveFiles="2"/>
  <target
    name="task2File"
    xsi:type="File"
    layout="${callsite} - ${message}"
    fileName="${basedir}../Data/debugLog2.txt"
    archiveAboveSize ="5000000"
    maxArchiveFiles="2"/>
</targets>