gpt4 book ai didi

c# - 为什么记录器建议每个类(class)使用一个记录器?

转载 作者:IT王子 更新时间:2023-10-29 03:37:55 25 4
gpt4 key购买 nike

根据 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 的操作方式相同。为什么这是一个好习惯?

最佳答案

使用 log4net,每个类使用一个记录器可以很容易地捕获日志消息的来源(即写入日志的类)。如果您没有为每个类配备一个记录器,而是为整个应用程序配备一个记录器,则您需要求助于更多的反射技巧来了解日志消息的来源。

比较以下内容:

每个类的日志

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 风格,你仍然这样做,但你可以为每个类做一次而不是每次调用一次,并消除严重的性能问题。

关于c# - 为什么记录器建议每个类(class)使用一个记录器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3143929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com