Saturday, 2 August 2014

Log Records

The Log Record wrap the message sent to the logger. LogRecord class provides number of methods to access various fields in log record like Log level, message, logger name, parameters passed etc.,

Getter methods in LogRecord class
Method Description
getLevel() Get the logging message level
getLoggerName() Get the source Logger's name.
getMessage() Get the raw message before formatting
getMillis() Get event time in milliseconds since 1970.
getParameters() Get the parameters to the log message.
getResourceBundle() Get the localization resource bundle
getResourceBundleName() Get the localization resource bundle name
getSequenceNumber() Get the sequence number.
getSourceClassName() Get the name of the class that issued the logging request.
getSourceMethodName() Get the name of the method that issued the logging request.
getThreadID() Get an identifier for the thread where the message originated.
getThrown() Get any throwable associated with the log record.

Setter methods in LogRecord class

Method Description
setLevel(Level level) Set the logging message level
setLoggerName(String name) Set the source Logger's name.
setMessage(String message) Set the "raw" log message, before localization or formatting.
setMillis(long millis) Set event time.
setParameters(Object[] parameters) Set the parameters to the log message.
setResourceBundle(ResourceBundle bundle) Set the localization resource bundle.
setResourceBundleName(String name) Set the localization resource bundle name.
setSequenceNumber(long seq) Set the sequence number.
setSourceClassName(String sourceClassName) Set the name of the class that issued the logging request.
setSourceMethodName(String sourceMethodName) Set the name of the method that issued the logging request.
setThreadID(int threadID) Set an identifier for the thread where the message originated.
setThrown(Throwable thrown) Set a throwable associated with the log event.

Example
import java.util.logging.*;

public class CustomFormat extends Formatter{
    @Override
    public String format(LogRecord record) {
       StringBuilder str = new StringBuilder();
       
       str.append("Logger Name : ");
       str.append(record.getLoggerName() + "\n");
       str.append("Level of the logger : ");
       str.append(record.getLevel() +"\n");
       str.append("Message : ");
       str.append(record.getMessage() +"\n");
       
       return str.toString();
    }
}

import java.io.IOException;
import java.util.logging.*;

public class FormatEx {
    static final Logger myLogger = Logger.getLogger("Simple Logger");
    
    public static void main(String args[]) throws IOException{
        Handler handler1 = new FileHandler("file1.out");
        CustomFormat format = new CustomFormat();
        
        myLogger.addHandler(handler1);
        myLogger.setLevel(Level.ALL);
        
        handler1.setFormatter(format);
        
        myLogger.log(Level.INFO, "Information Message");
        myLogger.log(Level.WARNING, "Warning Message");
        myLogger.log(Level.SEVERE, "Severe Message");
        
        handler1.close();
    }
}



Prevoius                                                 Next                                                 Home

Using Custom Formatters

By extending Formatter class we can provide custom formatters. Formatter class has abstract method format(LogRecord record), which formats the log record before publishing it to the external world.

import java.util.logging.*;

public class CustomFormat extends Formatter{
    @Override
    public String format(LogRecord record) {
       StringBuilder str = new StringBuilder();
       
       str.append("Logger Name : ");
       str.append(record.getLoggerName() + "\n");
       str.append("Level of the logger : ");
       str.append(record.getLevel() +"\n");
       str.append("Message : ");
       str.append(record.getMessage() +"\n");
       
       return str.toString();
    }
}

import java.io.IOException;
import java.util.logging.*;

public class FormatEx {
    static final Logger myLogger = Logger.getLogger("Simple Logger");
    
    public static void main(String args[]) throws IOException{
        Handler handler1 = new FileHandler("file1.out");
        CustomFormat format = new CustomFormat();
        
        myLogger.addHandler(handler1);
        myLogger.setLevel(Level.ALL);
        
        handler1.setFormatter(format);
        
        myLogger.log(Level.INFO, "Information Message");
        myLogger.log(Level.WARNING, "Warning Message");
        myLogger.log(Level.SEVERE, "Severe Message");
        
        handler1.close();
    }
}




Prevoius                                                 Next                                                 Home

Formatters

Formatters help to format the log records. Java logging package provides two built in formatters.

a. SimpleFormatter
b. XMLFormatter

Example: Using SimpleFormatter
import java.io.IOException;
import java.util.logging.*;

public class FormatEx {
    static final Logger myLogger = Logger.getLogger("Simple Logger");
    
    public static void main(String args[]) throws IOException{
        Handler handler1 = new FileHandler("file1.out");
        SimpleFormatter format = new SimpleFormatter();
        
        myLogger.addHandler(handler1);
        myLogger.setLevel(Level.ALL);
        
        handler1.setFormatter(format);
        
        myLogger.log(Level.INFO, "Information Message");
        myLogger.log(Level.WARNING, "Warning Message");
        myLogger.log(Level.SEVERE, "Severe Message");
        
        handler1.close();
    }
}

Example: Using XMLFormatter
import java.io.IOException;
import java.util.logging.*;

public class FormatEx {
    static final Logger myLogger = Logger.getLogger("Simple Logger");
    
    public static void main(String args[]) throws IOException{
        Handler handler1 = new FileHandler("file1.out");
        XMLFormatter format = new XMLFormatter();
        
        myLogger.addHandler(handler1);
        myLogger.setLevel(Level.ALL);
        
        handler1.setFormatter(format);
        
        myLogger.log(Level.INFO, "Information Message");
        myLogger.log(Level.WARNING, "Warning Message");
        myLogger.log(Level.SEVERE, "Severe Message");
        
        handler1.close();
    }
}




Prevoius                                                 Next                                                 Home

Log Levels Vs Log Hierarchy

1. If you don't set the level for a logger, then it inherits from the parent logger.

import java.io.IOException;
import java.util.logging.*;

public class LogHierarchy {
    static final Logger lev1 = Logger.getLogger("Level1");
    static final Logger lev2 = Logger.getLogger("Level1.Level2");
    static final Logger lev3 = Logger.getLogger("Level1.Level2.Level3");
    static Handler handler1, handler2, handler3;
        
    static void processData(){
        lev3.info("Processing started");
        /*Do Some processing here*/
        lev3.log(Level.SEVERE, "Severe Error Occured");
        lev3.info("Processing completed");
    }
    
    public static void main(String args[]) throws IOException{
        handler1 = new FileHandler("file1.out");
        handler2 = new FileHandler("file2.out");
        handler3 = new FileHandler("file3.out");
       
        lev1.addHandler(handler1);
        lev2.addHandler(handler2);
        lev3.addHandler(handler3);
       
        lev1.setLevel(Level.SEVERE);
        processData();
    }
}

Run the application, it creates 3 files 'file1.out', 'file2.out' and 'file3.out' and logs only severe messages.

2. If the logger set the level 'X', then the messages at level 'X' and higher only logged to higher levels of hierarchy.

import java.io.IOException;
import java.util.logging.*;

public class LogHierarchy {
    static final Logger lev1 = Logger.getLogger("Level1");
    static final Logger lev2 = Logger.getLogger("Level1.Level2");
    static final Logger lev3 = Logger.getLogger("Level1.Level2.Level3");
    static Handler handler1, handler2, handler3;
        
    static void processData(){
       lev3.log(Level.FINE, "Fine Message");
       lev3.log(Level.INFO, "Information Message");
       lev3.log(Level.WARNING, "Warning Message");
       lev3.log(Level.SEVERE, "Severe Message");
    }
    
    public static void main(String args[]) throws IOException{
        handler1 = new FileHandler("file1.out");
        handler2 = new FileHandler("file2.out");
        handler3 = new FileHandler("file3.out");
       
        lev1.addHandler(handler1);
        lev2.addHandler(handler2);
        lev3.addHandler(handler3);
       
        lev1.setLevel(Level.INFO);
        lev2.setLevel(Level.WARNING);
        lev3.setLevel(Level.SEVERE);
        processData();
    }
}

Even though loggers lev1 and lev2 set at levels INFO, WARNING, they don't log the FINE, WARNING and INFO messages. They log only SEVERE messages.



Prevoius                                                 Next                                                 Home

How Filters work with Log Hierarchy


If logger has a filter, then based on the filter the message passed to handler. If the message is accepted by filter, then it passed to corresponding handlers of the logger and all the handlers of parent loggers. But when a message is passed up the hierarchy, the message is not passed through the Filter's of the parent Logger's.

Will see it by an Example
import java.util.logging.*;
public class FilterSevereMsgOnly implements Filter {

    @Override
    public boolean isLoggable(LogRecord record) {
        return record.getLevel().equals(Level.SEVERE);
    }
    
}

import java.util.logging.*;

public class FilterWarningMsgOnly implements Filter {

    @Override
    public boolean isLoggable(LogRecord record) {
        return record.getLevel().equals(Level.WARNING);
    }    
}

import java.io.IOException;
import java.util.logging.*;

public class LogHierarchy {
    static final Logger lev1 = Logger.getLogger("Level1");
    static final Logger lev2 = Logger.getLogger("Level1.Level2");
    static final Logger lev3 = Logger.getLogger("Level1.Level2.Level3");
    static Handler handler1, handler2, handler3;
    
    static FilterSevereMsgOnly severe = new FilterSevereMsgOnly();
    static FilterWarningMsgOnly warning = new FilterWarningMsgOnly();
        
    static void processData(){
        lev3.info("Processing started");
        /*Do Some processing here*/
        lev3.info("Processing completed");
    }
    
    public static void main(String args[]) throws IOException{
        handler1 = new FileHandler("file1.out");
        handler2 = new FileHandler("file2.out");
        handler3 = new FileHandler("file3.out");
        
        lev1.setFilter(severe);
        lev2.setFilter(warning);
        
        lev1.addHandler(handler1);
        lev2.addHandler(handler2);
        lev3.addHandler(handler3);
       
        processData();
    }
}

Run the above application, it creates 3 files 'file1.out', 'file2.out' and 'file3.out'.

Even though the loggers lev1 and lev2 configure filters like they handle severe and warning messages respectively, All the info messages stored in file1.out and file2.out. Since when a message is passed up the hierarchy, the message is not passed through the Filter's of the parent Logger's. But if the handlers are configured with filters then they filter it before publishing to outside world. Will change the above application and see.

import java.io.IOException;
import java.util.logging.*;

public class LogHierarchy {
    static final Logger lev1 = Logger.getLogger("Level1");
    static final Logger lev2 = Logger.getLogger("Level1.Level2");
    static final Logger lev3 = Logger.getLogger("Level1.Level2.Level3");
    static Handler handler1, handler2, handler3;
    
    static FilterSevereMsgOnly severe = new FilterSevereMsgOnly();
    static FilterWarningMsgOnly warning = new FilterWarningMsgOnly();
        
    static void processData(){
        lev3.info("Processing started");
        /*Do Some processing here*/
        lev3.info("Processing completed");
    }
    
    public static void main(String args[]) throws IOException{
        handler1 = new FileHandler("file1.out");
        handler2 = new FileHandler("file2.out");
        handler3 = new FileHandler("file3.out");
        
        handler1.setFilter(severe);
        handler2.setFilter(warning);
        
        lev1.addHandler(handler1);
        lev2.addHandler(handler2);
        lev3.addHandler(handler3);
       
        processData();
    }
}




Prevoius                                                 Next                                                 Home

Logger Hierarchy

By using the name given to your logger, you can make a hierarchy.

For Example:
import java.util.logging.*;

public class LogHierarchy {
    public static void main(String args[]){
        Logger lev1 = Logger.getLogger("Level1");
        Logger lev2 = Logger.getLogger("Level1.Level2");
        Logger lev3 = Logger.getLogger("Level1.Level2.Level3");
        
        System.out.println(lev3.getParent().getName());
        System.out.println(lev3.getParent().getParent().getName());
        System.out.println(lev3.getParent().getParent().getParent().getName());
    }
}

Output
Level1.Level2
Level1

Logger.getLogger("Level1.Level2.Level3")

Each '.' in the name marks a level in the hierarchy.


getParent() return the parent for this Logger. Parent loggers should be created in the hierarchy, other wise getParent return empty string.

Example
import java.util.logging.*;

public class LogHierarchy {
    public static void main(String args[]){
        Logger lev3 = Logger.getLogger("Level1.Level2.Level3");
        System.out.println(lev3.getParent().getName());
    }
}

In the above program, loggers with name 'Level1' and 'Level1.Level2' are not created. So getParent() returns empty string.



Prevoius                                                 Next                                                 Home

Filters

Filters are associated with both loggers and handlers. Filters decide whether to forward or discard particular log record.

To create a filter a class must implement Filter interface.

public interface Filter {
    public boolean isLoggable(LogRecord record);
}

'isLoggable' check whether to publish or discard the given log record.

Application without loggers
import java.io.IOException;
import java.util.logging.*;

public class FilterEx {
    static final Logger myLogger = Logger.getLogger("FilterEx");
    
    static void processData(){
        myLogger.info("Started Processing data");
        myLogger.log(Level.SEVERE, "Got Severe Error");
        myLogger.log(Level.WARNING, "Warning Message");
        myLogger.info("Stopped Processing data");
    }
    
    public static void main(String args[]) throws IOException{        
        FileHandler handle1 = null;
        FileHandler handle2 = null;
        
        try{
            handle1 =  new FileHandler("Severe.out");
            handle2 =  new FileHandler("Warning.out");

            /* Adding handlersto myLogger */
            myLogger.addHandler(handle1);
            myLogger.addHandler(handle2);

            /* Setting Level to Logger */
            myLogger.setLevel(Level.ALL);

            processData();
        }
        finally{
            if(handle1 != null)
                handle1.close();
            if(handle2 != null)
                handle2.close();
        }
    }
}

Run the above Application and it creates two files 'Severe.out' and 'Warning.out' which contains SEVERE, INFO and WARNING messages.

but requirement like below.

'Severe.out' : Contains only severe messages.
'Warning.out' : Contains only warning messages.

To achieve the above functionality, filters are useful.

First will create two filters, one to filter warning messages and other to handle severe messages.
import java.util.logging.*;
public class FilterSevereMsgOnly implements Filter {

    @Override
    public boolean isLoggable(LogRecord record) {
        return record.getLevel().equals(Level.SEVERE);
    }
    
}

import java.util.logging.*;

public class FilterWarningMsgOnly implements Filter {

    @Override
    public boolean isLoggable(LogRecord record) {
        return record.getLevel().equals(Level.WARNING);
    }    
}

Instantiate the filters and set them to respective handlers.

import java.io.IOException;
import java.util.logging.*;

public class FilterEx {
    static final Logger myLogger = Logger.getLogger("FilterEx");
    static final FilterSevereMsgOnly severe = new FilterSevereMsgOnly();
    static final FilterWarningMsgOnly warning = new FilterWarningMsgOnly();
    
    static void processData(){
        myLogger.info("Started Processing data");
        myLogger.log(Level.SEVERE, "Got Severe Error");
        myLogger.log(Level.WARNING, "Warning Message");
        myLogger.info("Stopped Processing data");
    }
    
    public static void main(String args[]) throws IOException{        
        FileHandler handle1 = null;
        FileHandler handle2 = null;
        
        try{
            handle1 =  new FileHandler("Severe.out");
            handle2 =  new FileHandler("Warning.out");

            /* Adding handlersto myLogger */
            myLogger.addHandler(handle1);
            myLogger.addHandler(handle2);

            /* Setting Level to Logger */
            myLogger.setLevel(Level.ALL);
            
            handle1.setFilter(severe);
            handle2.setFilter(warning);

            processData();
        }
        finally{
            if(handle1 != null)
                handle1.close();
            if(handle2 != null)
                handle2.close();
        }
    }
}

After running the above Application, it creates two files,
'Severe.out' : Contains only SEVERE messages
'Warning.out' : Contains only WARNING messages.

handle1.setFilter(severe);
set the filter 'severe' to handler handle1.

handle2.setFilter(warning);
set the filter 'warning' to handler handle2.







Prevoius                                                 Next                                                 Home