Reading:  

What is Log4J. An absolute beginners tutorial.


Sample Program

Java Program Using log4j:

The below java code helps in understanding initialization and use of Log4j logging library. User need to create log4j2.xml file and use the same in the program.

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="WARN">
<appenders>
<File name="MyFile" fileName=" Applicationdemo.log ">
<PatternLayout pattern="%d{yyyy-mm-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</File>
</appenders>
<loggers>
<root level="debug">
<appender-ref ref="MyFile " level="info"/>
<appender-ref ref="MyFile" level="error"/>
</root>
</loggers>
</configuration>

Sample Class

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
 
public class Log4jConfigurationExample
{
  static final Logger logger_c = LogManager.getLogger(Log4jConfigurationExample.class.getName());

    public static void main(String[] args)
    {
        
 
        //log file and Log in console
        logger_c.debug("Configuration is successful Log4j appender!!");
        logger_c.info( "onfiguration is successful Log4j appender!!");
    }
} 

 

Compilation and Run:

Set the PATH and CLASSPATH for log4j2.xml file in the System. Save the program as Log4jConfigurationExample.java, compile and run the program. The result will be output on console and Applicationdemo.log in project folder as below.

Configuration is successful Log4j appender!!");

Configuration is successful Log4j appender!!");

 

 

 

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!