Log4j Configuration Eclipse


Here we are going to discussing Log4j configuration Eclipse with sample program.

Log4j Configuration Eclipse

Download Log4j Jar

Download Log4j jar from http://logging.apache.org/site/binindex.cgi 

Extract the downloaded jar file.

CreateLog4j Project

Create Java project as follows.

log1

Write project name like Log4jExample.

log2

Add downloaded log4j jar to build path by click on Add External Jar and click on OK

log3

Create Package

Create package like com.narayanatutorial.log4j as follows and click on Finish.

log4

Create Log4jExample.java

Create java class name like Log4jExample as follows and click on Finish

log5

Add the following code to java class.

package com.narayanatutorial.log4j;

import org.apache.log4j.Logger;

public class Log4jExample {

    private static final Logger logger = Logger.getLogger(Log4jExample.class);

    public static void main(String[] args) {

        logger.info("info log message...!");
    }
}

Create Log4j properties File

Create Log4j.properties file in the default package as follows and the following parameters to that file.

log = C:/logs/
log4j.rootLogger = INFO,stdout, FILE,

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

log9

Java Directory Structure

Find the final project structure as follows.

log10

Executing Java Program

Run the program and see the following output in the console and in the file.

Output from Console

log7

Output from File

log8

For more details click here

Reference Links:

Leave a Reply