Log4j Tutorial «Prev  Next»


Configuring Log4j Core Components

You can configure the core components using a configuration file. Configuring log4j involves assigning the Level, defining Appender, and specifying Layout objects in a configuration file. The log4j.properties file is a log4j configuration file which keeps properties in key-value pairs. By default, the LogManager looks for a file named log4j.properties in the CLASSPATH.
  1. The level of the root logger is defined as DEBUG. The DEBUG attaches the appender named X to it.
  2. Set the appender named X to be a valid appender.
  3. Set the layout for the appender X.

log4j.properties Syntax

Following is the syntax of log4j.properties file for an appender X:
# Define the root logger with appender X
log4j.rootLogger = DEBUG, X
# Set the appender named X to be a File appender
log4j.appender.X=org.apache.log4j.FileAppender
# Define the layout for X appender
log4j.appender.X.layout=org.apache.log4j.PatternLayout
log4j.appender.X.layout.conversionPattern=%m%n

log4j.properties Example

Using the above syntax, we define the following in log4j.properties file:
  1. The level of the root logger is defined as DEBUG. The DEBUG the appender named FILE to it.
  2. The appender FILE is defined as org.apache.log4j.FileAppender. It writes to a file named "log.out" located in the log directory.
  3. The layout pattern defined is %m%n, which means the printed logging message will be followed by a newline character.


Define the root logger with appender file
log4j.rootLogger = DEBUG, FILE
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=/log.out
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n

It is important to note that log4j supports UNIX-style variable substitution such as .

Debug Level

We have used DEBUG with both the appenders. All the possible options are:
  1. TRACE
  2. DEBUG
  3. INFO
  4. WARN
  5. ERROR
  6. FATAL
  7. ALL