Reading:  

What is Log4J. An absolute beginners tutorial.


Logging Methods used in Log4j 2

Logger class has different methods to handle activities of logging. The Logger class has two static methods for getting the Logger objects.

  • public static Logger getRootLogger();
  • public static Logger getLogger(String names);

Above two methods gives only the application instance's root logger without having a name. The next example shown below returns the name of logger based on class or package name.

static Logger log = Logger.getLogger(log4jExample.class.getName());

Logging Methods:

On creating instance of a logger there are several methods which are mentioned below to log messages. Some of the methods are as follows:

  • public void debug(Object message) : This prints message with Level.DEBUG.
  • public void error(Object message) : This prints message with  ERROR.
  • public void fatal(Object message) : This prints messages with Level.FATAL.
  • public void info(Object message) : This prints messages with Level.INFO.
  • public void warn(Object message) : This prints messages with Level.WARN.
  • public void trace(Object message) : This prints messages with Level.TRACE. 

Example

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
 
public class LogClassExample
{
    static final Logger logger_c = LogManager.getLogger(Log4jConfigurationExample.class.getName());
   public static void main(String[] args)
    {
		logger_c.debug("Message Debug!!");
		logger_c.info( " Message Info!!");
		logger_c.trace("Message Trace!!");
		logger_c.warn( " Message Warn!!");
		logger_c.error("Message Error!!");
		logger_c.fatal( " Message Fatal!!");
    }
}

Compile and run LogClassExample program and it would generate following output:

Message Debug!!
Message Info!!
Message Trace!!
Message Warn!!
Message Error!!
Message Fatal!!

 

Description

This tutorial is aimed at learners who want to get an understaind on what Log4J is and what it is used for. This tutorial have 10 part to it as shown below

  1. Overview    
  2. How to Install Log4J
  3. Understanding Architecture
  4. Getting started with Log4J Configuration
  5. Sample Program
  6. Logging Methods
  7. Understanding different Logging Levels
  8. Log4J log formatting
  9. How to log in files
  10. How to log in database using Log4J

We hope that this tutorial will help you out with Log4J. Please note that this tutorial is for absolute starters and does not go into much depth. Let us know how we can improve by sending  your feedback.



Prerequisites

A good understanding of Java programming language is required.

Audience

Absolute beginners

Author: Subject Coach
Added on: 7th Mar 2015

You must be logged in as Student to ask a Question.

None just yet!