Home » Log4j Example

Log4j Example

Let’s see a simple example for log4j. Follow the below steps:

1) Create a Java Project

  • Open the MyEclipse and go to File->New-> Java Project

Log4j Example

  • Enter the name of the project and click on the Finish button.

Log4j Example

2) Add the log4j jar File

  • To add the jar file of log4j, right-click on the created java project name and select Build Path -> Configure Build Path.

Log4j Example

  • Go to the Libraries tab and then click on the Add External JARs button.

Log4j Example

  • Select the log4j-1.2.17.jar file and click on OK button.

Log4j Example

3) Create a Java File

  • Create a new file on your java project and put the name of that file. Here my file name is Example.java.

Log4j Example

  • Copy the following code in your java file.

4) Create a log4j.properties File

Now, we need one configuration file i.e. log4j.properties file. For this, follow the given steps:

  • Right-click on your project name and go to New-> Folder

Log4j Example

  • Create a new file on that folder.

Log4j Example

  • Set the file name log4j.properties and click on Finish button.

Log4j Example

  • Go to the source tab from the bottom of the log.properties file and copy the following code.

5) Add the log4j.properties file to the Classpath

Now, we need to add the location of our log4j.properties file to the Classpath in Eclipse. Follow the below steps to do the configuration:

  • Right-click on your project name and select Run As -> Run Configurations

Log4j Example

  • Go to the Classpath tab and click on Advanced button.

Log4j Example

  • Select the Add Folders option and click on OK button.

Log4j Example

  • Browse the folder which you have created for log4j.properties file. Here, my folder name is Properties. Select that folder and click on OK, Apply then Run button.

Log4j Example

6) Compile and Run the Project

When you run the project you would get the output inside C:/usr/home/log4j/log.out file.

Log4j Example
Log4j Example

Output on the Console:

You can also see the output on the console. For this, you have to change the log4j.properties file. Copy the following code in your log4j.properties file:

Now, when you compile and run the project, you will get the same output on the console:

Output:

[main] DEBUG Example  - Hello this is a debug message  [main] INFO  Example  -   Hello this is an info message  

Next TopicLog4j Maven

You may also like