Software Development

How to configure Log4j to log to console

java Sort Enum Properties Monitor Directory File Lambda Expression parameter return types Validate XML String XSD ExecutorService AutoCloseable Try-With-Resources Convert LocalDateTime OffsetDateTime Run Codes Before Shutdown XML Tag Lambda PostgreSQL JDBC invoke JavaScript Applet SFTP Batch hang block main thread MySQL JDBC try-with-resources delete Unencrypted SoapFault Apache CXF Remove XML Element XSLT skip execute finally public static void main constructor fields Eclipse convert Iterator Stream StreamSupport XMLEncoder XMLDecoder rename P6Spy JDBC Example PDF Version JasperReports Run from Ant iReport Page Numbers Count entities persistence context hibernate
Okay, you wrote a lot of Log4j debug statements all over your codebase but do not want them to appear in QA and/or Production environment. How to do that? You need to configure Log4j by modifying log4j.xml. You could also use in place of log4j.xml but some advanced settings can only be set using the latter. Might as well use something that offers greater benefits.
In log4j, there are levels of logging. Each level represents the severity or type of log is being made. From ascending order of level, these are TRACE, DEBUG, INFO, WARN, ERROR, and FATAL. FATAL has the highest level; whereas TRACE sits on the lowest level.

Software Environment

  • Windows 7 Professional SP1
  • Eclipse – Kepler Release
  • Java 1.7 (1.7.0_67 – Windows x86)
  • Apache Log4j
    • Reference only log4j-1.2.16.jar

Your log4j.xml

This file should be included in the classpath.

Notice particularly the level or priority tags, they allow you to specify the minimum level of the log. If INFO is specified, only INFO, WARN, ERROR, and FATAL logs are displayed. In this configuration, only ERROR and FATAL logs will be shown.

Sample Usage

The first example uses a logger.error() method to log an error. This logs the message in the ERROR level.

Sample output

Another example tries to log a WARN message but that message is not displayed.


Notice “ERROR LoggerTest:6”? This is on line 6. The message logged on line 5 is nowhere on the console.


Got comments, or suggestions? Please visit our Facebook page!

You Might Also Like