伐木者为什么建议使用每类中的记录? [英] Why do loggers recommend using a logger per class?

查看:141
本文介绍了伐木者为什么建议使用每类中的记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据NLOG的文档:

大多数应用程序将使用每类中的一个记录,其中记录的名称相同的类的名称。

Most applications will use one logger per class, where the name of the logger is the same as the name of the class.

这是log4net的操作方式相同。为什么这是一个好的做法呢?

This is the same way that log4net operates. Why is this a good practice?

推荐答案

通过log4net的,使用每类中的一个记录器可以很容易地捕捉到日志消息(即类写入日志)的来源。如果没有每类中的一个记录,而是对整个应用设置一个记录器,你需要采取更多的思考的技巧,知道那里的日志消息的来源。

With log4net, using one logger per class makes it easy to capture the source of the log message (ie. the class writing to the log). If you don't have one logger per class, but instead have one logger for the entire app, you need to resort to more reflection tricks to know where the log messages are coming from.

比较如下:

using System.Reflection;
private static readonly ILog _logger = 
    LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);    

public void SomeMethod()
{
    _logger.DebugFormat("File not found: {0}", _filename);
}

每个应用(或类似)一个记录

Logger.DebugFormat("File not found: {0}", _filename); // Logger determines caller

-- or --

Logger.DebugFormat(this, "File not found: {0}", _filename); // Pass in the caller

使用第二个例子中,记录器将需要建立一个堆栈跟踪,看看谁在呼唤它,或者你的code总是在调用者传递。随着记录每类样式,你仍然这样做,但你可以做一次每类,而不是每一次呼叫,并消除严重的性能问题。

Using the second example, the Logger would need to build a stack trace to see who was calling it or your code would always have to pass in the caller. With the logger-per-class style, you still do this, but you can do it once per class instead of once per call and eliminate a serious performance problem.

这篇关于伐木者为什么建议使用每类中的记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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