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 FATAL
INFO: Shows messages classified as INFO, WARN, ERROR, and FATAL
WARN: Shows messages classified as WARN, ERROR, and FATAL
ERROR: Shows messages classified as ERROR and FATAL
FATAL: shows messages at a FATAL level only
OFF: The OFF Level has the highest possible rank and is intended to turn off logging.

The standard levels of Log4j are ordered as


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.

For example,

Create a maven based standalone project – logger

1. Below is the project’s pom.xml file with required log4j dependencies

2. Create log4j.xml file. Here I have kept only console appender. If you want you can also keep file appender.

3. Create Java main class

Now if you run the main class then you will get below output

We got the above output becasue I have set “priority value” as “warn”

Now if we change the “priority value” as “debug” and run the main class again

You will get below output

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.

For example,

Avoid logging at every place where a custom exception is thrown and instead log the custom exception message in its catch handler.

For example,

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.