Log4j Example

Log4j is a logging framework (APIs) written in Java, which is distributed under the Apache Software License. Logging is best way to do programming.We can track the application issue/flow so that it can easy to maintainable.

Components of Log4j

  • Logger
  • Layout
  • Appender

Logger

The Logger is top-level layer which provides the Logger object. The Logger object is responsible for capturing logging information.

Layout

This layer provides objects which are used to format logging information in different styles.

Appender

The Appender object is responsible for publishing logging information to various preferred destinations such as a database, file, console, etc.

log4j.properties

This file is used to provide configuration for log level,appender and layout information.

Here I am going take example to create logsĀ  both on Console and files.

Required jars

  • log4j-1.2.14.jar

Project Structure

log4j example

log4j.properties

This file need to add to src directory of project.

# Define the root logger with appender file
log4j.rootLogger = DEBUG,stdout

# Direct log messages to stdout
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

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=E:\\logging.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Log4jTest.java

Here first we need to get Logger object using getLogger() and then use debug(),fatal() or info() method for loggging.

import org.apache.log4j.Logger;

import java.io.*;
import java.sql.SQLException;
import java.util.*;

public class Log4jTest{

   /* Get actual class name to be printed on */
   static Logger log = Logger.getLogger(Log4jTest.class.getName());
   
   public static void main(String[] args)throws IOException,SQLException{
      log.debug("This is a debug message");
      log.info("This is an info message");
   }
}

Leave a Reply