为什么记录器建议每个类使用一个记录器?

编程入门 行业动态 更新时间:2024-10-26 22:16:16
本文介绍了为什么记录器建议每个类使用一个记录器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

根据 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.

更多推荐

为什么记录器建议每个类使用一个记录器?

本文发布于:2023-11-15 17:35:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1596548.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:记录器   建议

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!