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?
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?
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.
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
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.
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
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.