Logging Best Practices using Log4j

Log4j is a logging library for Java applications and the purpose of inserting log statements into the code is a low-tech method for debugging it. It may also be the only way because debuggers are not always available or applicable. This is often the case for distributed applications.Logging Levels

ALL: The ALL Level has the lowest possible rank and is intended to turn on all logging.TRACE: This level gives more detailed information than the DEBUG level.DEBUG: Shows messages classified as DEBUG, INFO, WARN, ERROR, and FATALINFO: Shows messages classified as INFO, WARN, ERROR, and FATALWARN: Shows messages classified as WARN, ERROR, and FATALERROR: Shows messages classified as ERROR and FATALFATAL: shows messages at a FATAL level onlyOFF: The OFF Level has the highest possible rank and is intended to turn off logging.

The standard levels of Log4j are ordered as

ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF

A logging request of a particular level is said to be enabled if that level is higher than or equal to the level of its logger.

So the logging of the message depends on the level that has been set to the logger.

Best Practices of Logging

It is recommended to declare the logger as static and final to ensure that every instance of a class shares the common logger object.
Write required code to check whether logging has been enabled at the right level.
Meaningful log messages that are relevant to the context should be logged.
You can use logging in the following scenarios,
– method entry (with method’s input parameter if any)
– method exit
– root cause message of exceptions at origin point.

Loggings which are used just for the purpose of debugging should be avoided.