Site icon Narayana Tutorial

Log4j Configuration Eclipse

Log4J

Log4J


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.

Write project name like Log4jExample.

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

Create Package

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

Create Log4jExample.java

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

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

Java Directory Structure

Find the final project structure as follows.

Executing Java Program

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

Output from Console

Output from File

For more details click here

Reference Links: