logging
Create custom Formatter for Logger handler
In this example we shall show you how to create custom Formatter for a Logger‘s Handler. The Handler usually uses a Formatter associated with it to format LogRecords. The Formatter takes a LogRecord and converts it to a string. LogRecord objects are used to pass logging requests between the logging framework and individual log Handlers. To create a custom Formatter to format LogRecords one should perform the following steps:
- Create a new CustomFormatter class that extends the Formatter and overrides its
format(LogRecord record)
method. In the example, the customFormatter uses a StringBuffer to append a prefix and a suffix to the record, using theappend(String str)
API method of the StringBuffer and returns a String representation of the LogRecord. - Create a new Logger instance.
- Create a FileHandler for the Logger to write to a specific file, and add it to the Logger with
addHandler(Handler handler)
API method. - Set the custom formatter to the handler with
setFormatter(Formatter newFormatter)
API method, to format its records,
as described in the code snippet below.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | package com.javacodegeeks.snippets.core; import java.util.logging.FileHandler; import java.util.logging.Formatter; import java.util.logging.LogRecord; import java.util.logging.Logger; public class CreateCustomFormatterForLoggerHandler { public static void main(String[] args) throws Exception { boolean append = false ; FileHandler handler = new FileHandler( "default.log" , append); Logger logger = Logger.getLogger( "com.javacodegeeks.snippets.core" ); logger.addHandler(handler); handler.setFormatter( new MyCustomFormatter()); logger.info( "custom formatter - info message" ); } private static class MyCustomFormatter extends Formatter { @Override public String format(LogRecord record) { StringBuffer sb = new StringBuffer(); sb.append( "Prefixn" ); sb.append(record.getMessage()); sb.append( "Suffixn" ); sb.append( "n" ); return sb.toString(); } } } |
Output:
Nov 19, 2011 4:11:51 PM com.javacodegeeks.snippets.core.CreateCustomFormatterForLoggerHandler main
INFO: custom formatter - info message
default.log
1 2 3 | Prefix custom formatter - info message Suffix |
This was an example of how to create custom Formatter for Logger handler in Java.