Is a logger per class or is a set of loggers that are accessed by the entire application perferred?

后端 未结 3 507
执笔经年
执笔经年 2021-01-04 05:41

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 logg

相关标签:
3条回答
  • 2021-01-04 05:53

    A logger in each class is better and more easy to extend. The reason is that defining one logger in one class easily separates the real logging api from the logger's configuration (format, persistence). 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, definition of "one logger per class" doesn't mean that each class uses 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 loggers referenced in the above code use the same logger instance is not clear. Normally, there is a configuration place (in a property file or in the code) that specifies whether the loggers in Foo and Bar share a logger instance.

    So "a logger in each class" just defines one logger for every class, but such loggers may refer to the same logger instance used in different classes

    0 讨论(0)
  • 2021-01-04 05:59

    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.

    0 讨论(0)
  • 2021-01-04 06:03

    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

    0 讨论(0)
提交回复
热议问题