Log4j ExampleLet'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
- Enter the name of the project and click on the Finish button.
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.
- Go to the Libraries tab and then click on the Add External JARs button.
- Select the log4j-1.2.17.jar file and click on OK button.
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.
- 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
- Create a new file on that folder.
- Set the file name log4j.properties and click on Finish button.
- 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
- Go to the Classpath tab and click on Advanced button.
- Select the Add Folders option and click on OK button.
- 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.
6) Compile and Run the Project When you run the project you would get the output inside C:/usr/home/log4j/log.out file.
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
|