Is a logger per class or is a set of loggers that

2019-02-16 10:42发布

I have a project in Java, and I create seven loggers that are accessed by a facade from every point of the program. But in the internet, I see a lot of examples witha a logger in each class.

What is the most recommended way to do logging?

标签: java oop logging
3条回答
不美不萌又怎样
2楼-- · 2019-02-16 11:14

I would recommend you to use some framework for logging, you can find a lot of them, being one of the most popular log4j, it will save you a lot of effort trying to reinvent the wheel, since they already come with most of best practices implemented.

A common best practice if you are using some logging framework like Log4J is to retrieve the logger in a static variable per class.

class Foo {
    private static final Logger log = Logger.getLogger( Foo.class );
}

With most logging frameworks you can define log levels (WARN, ERROR, DEBUG) and also pattern for the appenders so you can store the messages in different files filtering by different criterias.

Also with these frameworks you can easily set things like log rotation, which can be quite useful

查看更多
萌系小妹纸
3楼-- · 2019-02-16 11:16

a logger in each class is better and more easy to extend. the reason is that define one logger in one class separate the real logging api from the logger's configuration (format, persistence) easily. I have worked with more than one big and complex java software (> 1 million lines of code), they all use one logger per class.

also, define "one logger per class" doesn't mean each class use a different logger instance.

class Foo {
    private static final Logger log = Logger.getLogger( Foo.class );
}


class Bar {
    private static final Logger log = Logger.getLogger( Bar.class );
}

Whether the two logger used above using the same logger instance if not sure from the above code. Normally, there is a configuration place (in a property file or in program) that specify whether logger in Foo and Bar shares a logger.

So "a logger in each class" is just define one logger in every class, But such logger may referred to the same logger instance from different classes

查看更多
不美不萌又怎样
4楼-- · 2019-02-16 11:17

I use one logger per class for all technical aspects, e.g. logging, tracing, debugging, method in/out (private static final...). Often I used shared loggers for functional aspects, e.g. audit trails, security; public Logger in a shared class.

I'm not aware of standards or general best practices, but this approach worked well for me.

查看更多
登录 后发表回答