Home  >  Core Java

Example of FileHandler and ConsoleHandler in Java

By Arvind Rai, April 13, 2013
Logging in java can be done in file and console. FileHandler is used to log the message in specified file. And ConsoleHandler is used to log the message in console. We need to add Formatter to in handler object. Formatter can be XMLFormatter etc. Find the example respectively.
ConsoleHandlerTest.java
package com.concretepage;
import java.io.IOException;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.logging.XMLFormatter;
public class ConsoleHandlerTest {
    public static void main(String[] args) throws SecurityException, IOException {
        Logger logger = Logger.getLogger("conlog");
        Handler handler = new ConsoleHandler();
        handler.setFormatter(new XMLFormatter());
        logger.addHandler(handler);
        logger.info("logger info message");
    }
 }
Message on console.
Output
<?xml version="1.0" encoding="windows-1252" standalone="no"?>
<!DOCTYPE log SYSTEM "logger.dtd">
<log>
<record>
  <date>2013-04-11T12:40:58</date>
  <millis>1365664258105</millis>
  <sequence>0</sequence>
  <logger>conlog</logger>
  <level>INFO</level>
  <class>com.concretepage.ConsoleHandlerTest</class>
  <method>main</method>
  <thread>10</thread>
  <message>logger info message</message>
</record> 
FileHandlerTest.java
package com.concretepage;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.logging.XMLFormatter;
public class FileHandlerTest {
    public static void main(String[] args) throws SecurityException, IOException {

        Logger logger = Logger.getLogger("conlog");

        Handler handler = new FileHandler("c:\\concrte.log");

        handler.setFormatter(new XMLFormatter());

        logger.addHandler(handler);

        logger.info("logger info message");
    }
}
We can find a file as c:\concrte.log
and data will be as
Output
<?xml version="1.0" encoding="windows-1252" standalone="no"?>
<!DOCTYPE log SYSTEM "logger.dtd">
<log>
<record>
  <date>2013-04-11T12:26:35</date>
  <millis>1365663395261</millis>
  <sequence>0</sequence>
  <logger>conlog</logger>
  <level>INFO</level>
  <class>com.concretepage.FileHandlerTest</class>
  <method>main</method>
  <thread>10</thread>
  <message>logger info message</message>
</record>
</log> 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us