Write Log entries to log file (original) (raw)
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
2011-11-19T15:40:55 1321710055254 0 com.javacodegeeks.snippets.core SEVERE com.javacodegeeks.snippets.core.WriteLogEntriesToLogFile main 10 severe message 2011-11-19T15:40:55 1321710055322 1 com.javacodegeeks.snippets.core WARNING com.javacodegeeks.snippets.core.WriteLogEntriesToLogFile main 10 warning message 2011-11-19T15:40:55 1321710055323 2 com.javacodegeeks.snippets.core INFO com.javacodegeeks.snippets.core.WriteLogEntriesToLogFile main 10 info messageThis was an example of how to write Log entries to a log file in Java.
Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.