将 Log4j 记录器放入多个类中
我想将日志记录添加到我的程序中的相当多的类中。我是否需要添加行来为每个需要记录器的类定义记录器(我想避免在程序中传递记录器对象。
public class SomeClass {
static Logger logger = Logger.getLogger(SomeClass.class);
.......
如果我这样做,我可以通过此调用来“了解”其类(类似于 这个.class
或者有其他方法可以做到这一点
I want to add logging to quite few classes in my program. Do I need to add lines to define a logger to each class that needs a logger (I want to avoid passing logger object around my program.
public class SomeClass {
static Logger logger = Logger.getLogger(SomeClass.class);
.......
If I do this, can I get this call to "know" its class (something like this.class
Or are there alternative ways of doing this
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我发现方便的一种替代方法是创建一个为您创建 Logger 的抽象类:
然后按照惯例,从它继承的每个类都有一个正确配置的 Logger,并且您不必到处都有相同的、愚蠢的代码那个地方。项目中的大多数类都可以轻松地将其包含在其继承层次结构中,而对于那些不能包含在继承层次结构中的类,无论出于何种原因,您仍然可以回退到旧样式。您还可以添加不错的便捷方法,例如:
One alternative that I find handy is to make an abstract class that creates Loggers for you:
Then by convention, every class that inherits from it has a properly-configured Logger, and you don't have to have that same, stupid code all over the place. Most of your classes in a project can easily include this in their inheritance hierarchy, and for the ones that can't, for whatever reason, you can still fall back to the old style. You can also add nice convenience methods like:
是的,您需要向每个类添加行。
如果您的记录器是静态的(如您的示例),您需要每次都指定类,就像您所做的那样(SomeClass.class)。如果您使记录器成为非静态的,那么您可以使用 this.getClass() ,这将更加方便剪切和粘贴:
Yes you need to add lines to each class.
If your logger is static (as is your example) you need to specify the class each time like you did (SomeClass.class). If you make your logger non-static then you can use this.getClass() which would be more cut-n-paste friendly:
不,您不需要这样做,但这是一种习惯做法,而且是一种很好的做法。 Log4j 是围绕这个假设构建的,即人们会以这种方式使用它。它免费为您提供发出日志事件的位置,以及轻松管理整个记录器分支的日志级别。
理论上,您可以在多个类之间共享一个记录器,甚至只有一个全局记录器; Logger 是线程安全的,无论如何它都需要在附加对象时进行同步,因此您的性能不会受到影响。您也可以将其命名为任何您想要的名称,不需要使用类名。不过,出于我上面所说的原因,不建议这样做。
另外,您不需要将引用设为静态,因为 log4j 认为您只能创建一个具有给定名称的记录器,因此您不会将其存储在实例中而浪费内存多变的。
No, you don't need to do this, but this is an accustomed practice, and a good one. Log4j has been constructed around this assumption in mind, that people will use it this way. It gives you for free the location of the place where a log event was issued, as well as easy administration of log level for the whole branches of loggers.
Theoretically, you could share a logger among multiple classes, or even have only one global;
Logger
is thread safe, and it needs to synchronize upon appending object anyway, so your performance would not suffer. You can also name it anything you want, don't need to use the class name. It's not advised, though, for the reason I stated above.Also, you don't need to make the reference
static
, as log4j sees to it that you can only create one logger with a given name, you don't waste memory by having it stored in an instance variable.