Sometimes when I see my logging code I wonder if I am doing it right. There might be no definitive answer to that, but I have the following concerns:
Library Classes
I have several library classes which might log some INFO
messages. Fatal Errors are reported as exceptions. Currently I have a static logger instance in my classes with the class name as the logging name. (Log4j's: Logger.getLogger(MyClass.class)
)
Is this the right way? Maybe the user of this library class doesn't want any messages from my implementation or wants to redirect them to an application specific log. Should I allow the user to set a logger from the "outside world"? How do you handle such cases?
General logs
In some applications my classes might want to write a log message to a specific log not identified by the class' name. (I.e.: HTTP Request log
) What is the best way to do such a thing? A lookup service comes to mind...
I'm reviewing log-levels of an application and I'm currently detecting a pattern:
A log4j2-file defines a socket-appender, with a fail-over file-appender. And a console-appender. Sometimes I use log4j2 Markers when the situation requires it.
Thought an extra perspective might help.
The following is the guidelines I follow in all my projects to ensure good performance. I have come to form this set of guidelines based on the inputs from various sources in the internet.
As on today, I believe Log4j 2 is by far the best option for logging in Java.
The benchmarks are available here. The practice that I follow to get the best performance is as follows:
Do not use String concatenation. Use parameterized message as shown above
Use dynamic reloading of logging configuration so that the application automatically reloads the changes in the logging configuration without the need of application restart
Do not use
printStackTrace()
orSystem.out.println()
The application should shut down the logger before exiting: