Saturday 2 August 2014

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

No comments:

Post a Comment