Example of FileHandler and ConsoleHandler in Java
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"); } }
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>
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"); } }
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>