How to use Log4j in Eclipse

Home > Search > How-to
  by

This assumes you have already downloaded and installed Log4j on your system that Eclipse is running on.

  1. In Eclipse, select Window > Preferences.
  2. In the left panel of the Preferences window, expand Java > Build Path and select User Libraries.
  3. Select New.
  4. Name the library Log4j and select OK.
  5. Select Add External JARs, select log4j-api-<version>.jar and select OK.
  6. Highlight Log4j.
  7. Select Add External JARs, select log4j-core-<version>.jar and select OK.
  8. Select Apply and Close.

The Log4j library with the two JARs should now be displayed.

 

Add the Log4j library to your project.

  1. In the left panel of Eclipse, highlight the project that you want to use Log4j.
  2. Select Project Properties.
  3. In the left panel of the dialog box, highlight Java Build Path.
  4. Select the Libraries tab.
  5. Select Add Library.
  6. Highlight User Library and select Next.
  7. Check Log4j and select Finish.
  8. Select Apply and Close.

The Log4j library should now be displayed.

 

Create a configuration file for Log4j.

  1. Right-click on your project and select New > Folder.
  2. Name the new folder Log4j.
  3. Right-click on the Log4j folder and select New File.
  4. Name the new file Log4j.xml and select Finish.
  5. Add the following markup to the Log4j.xml file (replace Beta with the name of your project).
<?xml version="1.0" encoding="UTF-8"?> 
<Configuration> 
  <Appenders> 
    <Console name="STDOUT" target="SYSTEM_OUT"> 
      <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/> 
    </Console> 
  </Appenders> 
  <Loggers> 
    <Logger name="Beta" level="info"/> 
    <Root level="trace"> 
      <AppenderRef ref="STDOUT"/> 
    </Root> 
  </Loggers> 
</Configuration>

 

Configure the Log4j folder so that it can be used as a source.

  1. In the left panel of Eclipse, highlight your project.
  2. Select Project Properties.
  3. In the left panel of the dialog box, highlight Java Build Path.
  4. Select the Source tab.
  5. Select Add Folder, check your Log4j folder, and select OK.
  6. Select Apply and Close.

 

 

To log events to Log4j, in one of your Java classes, import the following packages.

import org.apache.logging.log4j.Logger; 
import org.apache.logging.log4j.LogManager;

 

df



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments