在NLog中添加方法名称 [英] Adding method name in NLog

查看:477
本文介绍了在NLog中添加方法名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NLog并遵循建议的模式,即在每个类上声明一个日志,以便能够跟踪已将哪个类/方法写入了日志.我确实发现每个日志写入时都有一些顶级堆栈跟踪"非常有用.

I am using NLog and following the recommended pattern of having a log declare on each class, for the purpose of being able to track which class/method has written to the log. I do find this very useful to have a bit of a top level 'stack trace' with each log write.

我的代码过去通常是这样的:

My code used to look like this:

class SomeClass {

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

}

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

I recently had the requirement my single project to write to 3 separate log files, and to do this, I added multiple loggers and targets as specified here: https://stackoverflow.com/a/21711838/191206

但是,现在在我的日志文件中,我丢失了类级别名称.现在,它仅写入我在NLog.config中指定的日志名称.我已经考虑过简单地添加自己的方法名称并调用

However, now in my log files, I have lost the class level name. It now just writes the log name that I specified in the NLog.config. I've considered simply adding the method name myself with a call to

System.Reflection.MethodBase.GetCurrentMethod(); // use Name property

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

or using something else in Reflection like this

但是,我想知道NLog是否内置了我所缺少的东西?我只看到Debug()方法可以写入带有参数&的字符串.可选格式.

However, I'm wondering if NLog has something built into this that I'm missing? The Debug() method I only see the ability to write a string, with parameters & optionally formatted..

这是NLog内置的吗?

Is this built into NLog?

推荐答案

有一个内置的名为${callsite} 的布局渲染器,可用于在日志条目中包括调用站点信息(类名,方法名和源信息):

There is a built in layout renderer called ${callsite} that you can use to include the call site information (class name, method name and source information) in your log entries:

<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>

这篇关于在NLog中添加方法名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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