What is Log4J?

This tutorial is going to explain about Apache Log4J.

  • Apache Log4J is logging framework provided by Apache Software Foundation.
  • Log4j is a Java logging framework used in Java programming and Java applications to debug any error/exception in the logs.
  • Log4j has various built-in types of logging debug levels, see below low to high order.

Log4J Logging Levels:

Logging Levels Description
OFF The highest possible rank and is intended to turn off logging.

 

FATAL Severe errors that cause premature termination to lead the application to abort.
ERROR Error will allow the application to continue running (unexpected conditions/ runtime errors).

 

WARN Runtime situation that is undesirable or unexpected, almost error condition.
INFO Info will be immediately visible to console.
DEBUG Detailed information on the flow through the system, all are written to logs, this level is very useful to debug the program/application.

 

TRACE More detailed information and those are written to logs, more than debug level.
ALL All logging levels, including custom levels.

 

 Step 1

In Eclipse create a Java Project (File > New > Java Project)

Step 2

1 . Create a class file > java

/**

*/

package com.rrmaha.test;

import org.apache.log4j.Logger;

/**

* @author rrmaha.com

*/

public class LogTest {

static final Logger logger = Logger.getRootLogger();

public static void main(String[] args) {

logger.debug(“Test debug message”);

logger.info(“Test info message”);

logger.warn(“Test warn message”);

logger.error(“Test error message”);

logger.fatal(“Test fatal message”);

}

}

2. Create a file properties file > properties

# Define the root logger with appender file

log = /usr/home/log4j

log4j.rootLogger = debug, FILE

 

# Define the file appender

log4j.appender.FILE=org.apache.log4j.FileAppender

log4j.appender.FILE.File=${log}/log.out

 

# number of log files to keep before deleting the oldest one

log4j.appender.MaxBackupIndex=25

log4j.appender.MaxFileSize=1KB

log4j.appender=org.apache.log4j.RollingFileAppender

log4j.appender.file=jpe.log

 

# Define the layout for file appender

# Log message layout: date-time [thread] priority category – message lineTerminator

log4j.appender.FILE.layout=org.apache.log4j.PatternLayout

log4j.appender.FILE.layout.conversionPattern=%d{dd MMM yyyy HH:mm:ss} [%t] %-5p %c – %m%n

 

3. Create a folder

/usr/home/log4j

4. Create output file name(log file name)

log.out

5. Add log4j jar file > log4j-1.2.16.jar

Step 3

Step 4

Open a file > \usr\home\log4j\ log.out

04 May 2017 19:59:27 [main] DEBUG root – Test debug message

04 May 2017 19:59:27 [main] INFO  root – Test info message

04 May 2017 19:59:27 [main] WARN  root – Test warn message

04 May 2017 19:59:27 [main] ERROR root – Test error message

04 May 2017 19:59:27 [main] FATAL root – Test fatal message