Log4j:- Using A Configuration File

Background

In our first Log4J sample, we relied on the default configuration.

Let us take another pebble step.

For this iteration, we will use a very small configuration file.

Lineage

  1. Java:- JDK – Installing Java JDK on MS-Windows
    Link
  2. HelloWorld In Java
    Link
  3. Log4J – Preparation
    Link
  4. HelloWorld In Log4J
    Link

Application

Class

helloLog4j.java


/*
    Import Apache log4j Packages
*/
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class helloLog4j
{

    /*
        Declare Variables
    */   
    static Logger log = null;
    
    public static void main(String[] args)
    {
       
        /*
            Declare Variables
        */
        Exception objExceptionNull = null;

        // configures the root logger
        log = LogManager.getRootLogger();  

        /*
            Get Logger passing on category
                category:- ClassName
        */    
        //log = LogManager.getLogger(helloLog4j.class);
    
        objExceptionNull = new NullPointerException("NullError");
        
        metadata();
        
        log.debug("Hello this is a debug message");

        log.info("Hello this is an info message");
        
        log.error
        (
              "Error Message Logged !!!"
            , objExceptionNull
        );
                
    } // function main
   
    
    static void metadata()
    {
       
        /*
            Declare Variables
        */
        String strLog4JVersion = null;
        String FORMAT_LOG4J_VERSION = "Log4j Version Number is %s %n";

        /*
            How can I check the version number of Log4j in a .jar file?
            Bhushan
            https://stackoverflow.com/questions/70333560/how-can-i-check-the-version-number-of-log4j-in-a-jar-file
        */
        
        /*
            Get log4J Version Number
        */
        strLog4JVersion
            = org.apache.log4j.Layout.class.getPackage().getImplementationVersion();
        
        /*
            If we have log4J Version Number, Log the retrieved version number
        */
        if (strLog4JVersion != null)
        {
                           
            System.out.printf
            (
                  FORMAT_LOG4J_VERSION
                , strLog4JVersion
            );
            
        }
       
   } //metadata
   
   
}

Configuration

log4j2.xml

Outline

  1. Configuration
    • Attributes
      • status
        • Definition
          • This appender will not log any messages with priority lower than the one specified here even if the category’s priority is set lower.
          • This is useful to cut down the number of messages, for example, in a file log while displaying all messages on the console.
        • Sample
          • WARN
      • monitorInterval
        • The log file is checked every 30 seconds
        • If the file’s content has been changed, it is incorporated
  2. Properties
    • Property
      • Attribute
        • name
          • LOG_PATTERN
      • Item
        • Pattern
          • Sample
            • %d{yyyy-MM-dd HH:mm:ss.SSS} %5p : %m%n%ex
          • Pattern Format
            • %d{yyyy-MM-dd HH:mm:ss.SSS}
            • %p
              • Message Priority ( FATAL, ERROR, WARN, INFO, DEBUG, or CUSTOM )
            • %m
              • Message
            • %n
              • New Line
            • %ex
              • Exception
  3. Appenders
    • Console
      • Attribute
        • name
          • ConsoleAppender
        • target
          • SYSTEM_OUT
        • Follow
          • true
    • File
      • Attribute
        • fileName
          • Sample
            • logs\app.log
  4. Loggers
    • Root
      • Attribute
        • level
          • info
      • AppenderRef
        • Attribute
          • ref
            • ConsoleAppender
            • FileAppender
    • Category
      • Attribute
        • level
          • info
      • AppenderRef
        • Attribute
          • ref
            • ConsoleAppender
            • FileAppender

File Content


<?xml version="1.0" encoding="UTF-8"?>

<Configuration 
    status="WARN" 
    monitorInterval="30"
    >
    
    <Properties>
        <Property name="LOG_PATTERN">
            %d{yyyy-MM-dd HH:mm:ss.SSS} %5p : %m%n%ex
        </Property>
    </Properties>
    
    <Appenders>
    
        <Console 
            name="ConsoleAppender" 
            target="SYSTEM_OUT" 
            follow="true"
        >
            <PatternLayout>
                <Pattern>${LOG_PATTERN}</Pattern>
            </PatternLayout>
        </Console>
        
        <File name="FileAppender" 
              fileName="logs\app.log"
        >
            <PatternLayout>
                <Pattern>${LOG_PATTERN}</Pattern>
            </PatternLayout>
        </File>
        
        
    </Appenders>
    
    <Loggers>

        <Root level="info">
        
            <AppenderRef 
                ref="ConsoleAppender" 
                />
            
            <AppenderRef 
                ref="FileAppender" 
                />
            
        </Root>
        
    </Loggers>
    
</Configuration>

 

Glossary

Pattern Format

Item Format Meaning / Sample Impact
Newline %n Newline Negligible
Log Message %m Passed by the developer to the logging method Negligible
Priority %p Message Priority ( FATAL, ERROR, WARN, INFO, DEBUG, or CUSTOM ) Negligible
Time %r Time expounded since the application started running Negligible
% %% As the % sign is the prefix used by each format tag, please request the % itself by escaping it using %% Negligible
Category Name %c Category Name Negligible
Current Thread %t Multi-thread application Negligible
Nested Diagnostic Thread ( NDC ) %x NDC that is supplied by the developer Negligible
Date and Time %d Date and Time.  %d{ISO8601}, %d{DATE}, %d{ABSOLUTE}, %d{HH:mm:ss, SSS}, %d{dd MMM yyyy HH:mm:ss} Slow
Java Source File Name %F The file name for the java source file Slow
Java Class Name %C Java class name.
%C{1}:- The class name
%C:- Full class name including the package name
Slow
Java Method Name %M Java’s class method name Slow

 

Commended

Crediting Vipan Singla.

 

Referenced Materials

  1. Vipan Singla
    • Don’t Use System.out.println!, Use Log4j
      Link

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s