How to use Log4j in Java code

suggest change

Log4j 1 and Log4j 2 do not use the same logger type. classname.class is not a class literal. Concatenating null does not throw NullPointerException; it inserts the text null.

Log4j 1 (org.apache.log4j.Logger) has no {} parameter overload. Guard expensive concatenation with isInfoEnabled when that level may be off:

private static final org.apache.log4j.Logger logger =
    org.apache.log4j.Logger.getLogger(MyClass.class);

if (logger.isInfoEnabled()) {
    logger.info("Information about some param: " + parameter);
}

// The second argument must be a Throwable. It is logged as the exception, not concatenated.
logger.error("Information about some error: ", exception);

Log4j 2 (org.apache.logging.log4j.Logger) formats {} only when the level is enabled, so the isInfoEnabled test is unnecessary for this call:

private static final org.apache.logging.log4j.Logger logger =
    org.apache.logging.log4j.LogManager.getLogger(MyClass.class);

logger.info("Information about some param: {}", parameter);
logger.error("Information about some error: ", exception);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents