为什么记录器建议每个类使用一个记录器? [英] Why do loggers recommend using a logger per class?

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

问题描述

根据 NLog 的文档:

As per NLog's documentation:

大多数应用程序会为每个类使用一个记录器,其中记录器的名称与类的名称相同.

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

使用第二个示例,Logger 需要构建堆栈跟踪以查看谁在调用它,否则您的代码将始终必须传入调用者.使用 logger-per-class 样式,您仍然可以这样做,但您可以为每个类执行一次,而不是每次调用一次,从而消除严重的性能问题.

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天全站免登陆