Java Programing laungage

java.util Projects

java.util Project 1

Setting the Formatter of Logger Handler

This programming tutorials, we shall be discussed how to set the formatter of a logger handler. The Java provides a logger handler that uses a formatter method for writing log records for a log file that can be either xml file or other.

Previous Home Next

There are two types of defined formatters one is SimpleFormatter and another is XMLFormatter. Simple Formatter is used to write a file with simple text while XMLFormatter writes the file into xml format.

There are two Example are available in this page of tutorials. First example is used to write for log records into a log file in simple text format and Second example is used for writing log records in a XML file format.

Code Descriptions

SimpleFormatter()

It is the constructor method of the SimpleFormatter class which is the class of java.util.logging; package. This constructor writes the detail message or information of log records to the file under stable format typically one or two lines only. The file is written in that format which is more readable for user.

fhand.setFormatter()

This method is used to set formatter into Handler.

Example1


package r4r;
import java.io.IOException;
import java.util.*;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class setformatertest1 {
public static void main(String[] args) {
setformatertest1 sft = new setformatertest1();
 }
 public setformatertest1(){
 Logger log = Logger.getLogger("R4RTechSoft solution");
 try{
 FileHandler fhand = new FileHandler("sam.log", true);
 fhand.setFormatter(new SimpleFormatter());  
 log.addHandler(fhand);
 log.info("This is info message");
 log.warning("This is warning message");
 }
 catch (IOException e){}
 }
}

Example2


package r4r;
import java.io.IOException;
import java.util.*;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.XMLFormatter;
public class setformatertest2 {
public static void main(String[] args) {
Logger log = Logger.getLogger("R4RTechSoft Solution");
try{
FileHandler xhand = new FileHandler("Sam.xml",true);
xhand.setFormatter(new XMLFormatter());
log.addHandler(xhand);
log.info("This is info message");
log.warning("This is warning message");
}
catch (IOException e){}
}
}

Previous Home Next