logging
Write Log entries to log file
With this example we are going to demonstrate how to write Log entries to a log file. In short, to write Log entries to a log file you should:
- Create a new FileHandler to write to a specific file.
- Create a new Logger instance with
getLogger(String name)
API method of Logger. - Add the handler to the Logger, with
addHandler(Handler handler)
API method of Logger. - Invoke log methods of Logger to log messages in different levels, such as
warning(String msg)
,info(String msg)
andconfig(String msg)
API methods. All logs will be written to the specified file by the FileHandler.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.util.logging.FileHandler; import java.util.logging.Logger; public class WriteLogEntriesToLogFile { public static void main(String[] args) throws Exception { boolean append = true; FileHandler handler = new FileHandler("default.log", append); Logger logger = Logger.getLogger("com.javacodegeeks.snippets.core"); logger.addHandler(handler); logger.severe("severe message"); logger.warning("warning message"); logger.info("info message"); logger.config("config message"); logger.fine("fine message"); logger.finer("finer message"); logger.finest("finest message"); } }
Output:
Nov 19, 2011 3:40:55 PM com.javacodegeeks.snippets.core.WriteLogEntriesToLogFile main
SEVERE: severe message
Nov 19, 2011 3:40:55 PM com.javacodegeeks.snippets.core.WriteLogEntriesToLogFile main
WARNING: warning message
Nov 19, 2011 3:40:55 PM com.javacodegeeks.snippets.core.WriteLogEntriesToLogFile main
INFO: info message
default.log
<?xml version="1.0" encoding="windows-1252" standalone="no"?> <!DOCTYPE log SYSTEM "logger.dtd"> <log> <record> <date>2011-11-19T15:40:55</date> <millis>1321710055254</millis> <sequence>0</sequence> <logger>com.javacodegeeks.snippets.core</logger> <level>SEVERE</level> <class>com.javacodegeeks.snippets.core.WriteLogEntriesToLogFile</class> <method>main</method> <thread>10</thread> <message>severe message</message> </record> <record> <date>2011-11-19T15:40:55</date> <millis>1321710055322</millis> <sequence>1</sequence> <logger>com.javacodegeeks.snippets.core</logger> <level>WARNING</level> <class>com.javacodegeeks.snippets.core.WriteLogEntriesToLogFile</class> <method>main</method> <thread>10</thread> <message>warning message</message> </record> <record> <date>2011-11-19T15:40:55</date> <millis>1321710055323</millis> <sequence>2</sequence> <logger>com.javacodegeeks.snippets.core</logger> <level>INFO</level> <class>com.javacodegeeks.snippets.core.WriteLogEntriesToLogFile</class> <method>main</method> <thread>10</thread> <message>info message</message> </record> </log>
This was an example of how to write Log entries to a log file in Java.