问题描述
这似乎更清洁的申报记录,并调用 LogManager.GetLogger
在基类让大家谁是继承可以使用它。然而,在log4net的网站和其他博客就像本博客帖子它指出,最好是每声明类中的一个记录器,因为:
It seems cleaner to declare a logger and call LogManager.GetLogger
in a base class so that everyone who is inheriting can use it. However, on log4net site and other blogs like in this blog post it states that it is better to declare one logger per class because:
您可以使用记录器这种方式来隔离在你的对象记录的关切,我完全推荐你这样做。这将使你掐死,并使用log4net的的层次配置机制从单个记录仪的输出直接登录。
这是否意味着,如果我把它放在基类,它将使该记录器的一个瓶颈?
Does this mean if I put it in base class, it will make that logger a bottleneck?
如果是这样,有没有其他的解决方案,还是我只需要创建每班一个记录?
If so, are there other solutions or do I just have to create a logger per class?
推荐答案
该职位是不会告诉你使用一个不同的记录器在每一个派生类,但是每个类类型不同的记录器。你可以,但不必在每一个派生类中使用一个新的记录器实例。
The post is not telling you to use a different logger in each derived class, but instead a different logger per class type. You can, but don't have to use a new logger instance in each derived class.
看它是,它可能会造成混乱有实例化的同时(因为基地之一将仍然存在)两个独立的记录器,尤其是如果你使用相同的记录器名称隐藏基地之一的一种方法。你的基类方法(而不是覆盖)将仍引用基静态记录仪,并重写的人会使用不同的功能。
One way to look at it is that it might be confusing to have two separate loggers instantiated at the same time (because the base one will still exist), especially if you hide the base one using the same logger name. Your base class methods (not overridden) will still reference the base static logger, and overridden ones will use a different one.
此外,文章实例化记录是这样的:
Also, the article instantiates the logger like this:
static ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType );
而稍微简单的方法可能是使用:
while a slightly simpler way might be to use:
static readonly ILog Log = LogManager.GetLogger(typeof(YourClass));
首先,它标志着只读
,这意味着你将无法改变不慎,一旦被初始化的领域。而使用类型将相同的方式工作与反思,但稍快(解决在编译时)。 Visual Studio中也将自动更新类的名称,如果你选择重命名它(这不是吗,你使用的字符串过载)。
First of all, it's marked readonly
, meaning you won't be able to change the field accidentally, once initialized. And using the type will work the same way as with reflection, but slightly faster (resolved at compile time). Visual Studio will also update the class name automatically if you choose to rename it (which it wouldn't it you used the string overload).
这篇关于我应该声明log4net的记录每一次类或基类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!