Log4j2 – Basic Logging For Java Development – Eclipse

Log4j2_Example

The purpose of this exercise is to implement Log4j2 as a console logger and file logger for Java development.

1. Download apache-log4j-2.3-bin.zip

2. In Windows explorer create a /lib/ folder in you project parent folder if one does not exist, typically the same folder that contains your /src/ package folder.

3. In Windows explorer move log4j-api-2.3. and log4j-core-2.3 jar files from the zip into the /lib/ folder you created

4. Right click and refresh your project in Eclipse Package Explorer to make the /lib/ folder visible

5. Right click log4j-api-2.3 and log4j-core-2.3 in the /lib/ folder and select Build Path -> Add to Build Path

  • /lib/ is not a package folder, /src/ is a package folder

6. Create log4j2.xml in your project /src/ folder so it is part of your class path – this is your configuration file.

 <?xml version="1.0" encoding="UTF-8"?>
 <Configuration status="DEBUG">
 <Appenders>
 <Console name="Console" target="SYSTEM_OUT">
 <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
 </Console>
 <File name="MyFile" fileName="all.log" immediateFlush="false" append="false">
 <PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
 </File>
 </Appenders>
 <Loggers>
 <Root level="debug">
 <AppenderRef ref="Console" />
 <AppenderRef ref="MyFile"/>
 </Root>
 </Loggers>
 </Configuration>

7. Create a text file in your project parent directory and save it as all.log

For some unknown reason the logger didn’t work correctly the first time and even though the files were in the right place and the setting were correct. The logger couldn’t find the configuration file initially. I tried moving log4j2.xml to /src/main/resources/ with no success. Only after moving it back to /src/ did it finally kick in. I found this to be the same case when I implemented it for the first time in another project.