Software Development

How to configure Log4j to log to console

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 log4j.properties 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.

Outputs:

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

 

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like