Log4j Setup Tutorial

Hey guys,

here’s a short tutorial that shows you how to set up log4j in your Eclipse Java Project.

In the beginning, download log4j here: http://logging.apache.org/log4j/2.x/download.html
To use log4j in your code, you need two libraries:

log4j-api-2.0-beta7.jar
log4j-core-2.0-beta7.jar

Put them in your classpath:
1. Create a new folder in your project called „lib
2. Copy both jars into the lib folder.
3. Open your MANIFEST.MF
4. Go to Runtime
5. In the section „Classpath“ click on add
6. Select both both log4j*.jar files
7. Click ok

Now, go to one of your Java classes and import:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

To use your logger, execute the following statements in a function:
Logger logger = LogManager.getLogger(this.getClass().getSimpleName());
logger.fatal("fatal");
logger.error("error");
logger.warn("warn");
logger.info("info");
logger.debug("debug");
logger.trace("trace");

The logger is working. But what if we want to change some settings like style or output?
For configuring the logger for your own purpose, create a folder properties in your project and add a new file called log4j2.xml with the following content to it.
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="warn">
    <appenders>
        <Console name="Console" target="SYSTEM_OUT">
           <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36}-%msg%n"/>
        </Console>
    </appenders>
    <loggers>
        <root level="debug">
            <appender-ref ref="Console" />
        </root>
    </loggers>
</configuration>

Now, put this config file into the classpath:
1. Go back to your MANIFEST.MF -> Runtime -> Classpath -> add
2. Select your properties folder and click OK

All settings made inside this file are applied to your logger. The most important one is <root level="trace"> It defines, which messages are printed to the console. The following five log levels are available:
all > trace > debug > info > warn > error > fatal > off
The levels that are on the right side of your chosen level are not displayed. For example: logger.trace(„trace“) won’t be displayed if you choose debug in <root level="..." >.

Hope it’s useful 🙂

Advertisements

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden / Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden / Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden / Ändern )

Google+ Foto

Du kommentierst mit Deinem Google+-Konto. Abmelden / Ändern )

Verbinde mit %s