【问题标题】:Adding method name in NLog在 NLog 中添加方法名称
【发布时间】:2014-03-23 19:58:26
【问题描述】:

我正在使用 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 中的吗?

【问题讨论】:

  • 你检查过${callsite} layout renderer 吗?
  • 就是这样 - 你能用那个解决方案回答这个问题,以便我给你适当的信任吗?谢谢

标签: c# nlog


【解决方案1】:

您可以使用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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 2019-01-21
    相关资源
    最近更新 更多