Configuration File for Apache Log4j

Q

How to write a simple configuration file for Apache Log4j? I just want to use the basic functionalities to specify the log file name and the log level.

✍: FYIcenter.com

A

Below is a simple configuration file, log4j2.xml, that support the Log4j 2 API:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright (c) FYIcenter.com -->
<Configuration status="WARN">
 <Appenders>
  <File name="MyAppender" fileName="HelloLog4j2.log" 
   bufferedIO="true">
   <PatternLayout 
    pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
  </File>
  <Console name="Screen" target="SYSTEM_OUT">
   <PatternLayout 
    pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
  </Console>
 </Appenders>
 <Loggers>
  <Logger name="fyiLogger" level="debug" additivity="true">
   <AppenderRef ref="MyAppender"/>
  </Logger>
  <Root level="error">
   <AppenderRef ref="Screen"/>
  </Root>
 </Loggers>
</Configuration>

This sample configuration file log4j2.xml does the following:

  • It defines a named logger "fyiLogger" and the Root logger.
  • It sets the "fyiLogger" logger level to "debug" and higher.
  • It sets the Root logger level to "error" and higher.
  • It defines a Console appender "Screen" and a File appender "MyAppender".
  • It sets both appenders with the same logging string pattern.

 

⇒ Running Program with Apache Log4j Configuration

⇐ Running Program with Apache Log4j

⇑ Using Apache Log4j in Java Programs

⇑⇑ FAQ for Apache Log4j

2015-11-11, 1665👍, 0💬