To create a custom Formatter
we need to extends the java.util.logging.Formatter
abstract class and implements the format(LogRecord)
method. In the method then we can format the log message stored in the LogRecord
to match our need.
The java.util.logging.Formatter
class also have the getHead(Handler)
and getTail(Handler)
which can be overridden to add a head and a tail to our log message.
package org.kodejava.example.util.logging;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.*;
public class LogCustomFormatter {
public static void main(String[] args) {
Logger logger = Logger.getLogger(LogCustomFormatter.class.getName());
logger.setUseParentHandlers(false);
MyFormatter formatter = new MyFormatter();
ConsoleHandler handler = new ConsoleHandler();
handler.setFormatter(formatter);
logger.addHandler(handler);
logger.info("Example of creating custom formatter.");
logger.warning("A warning message.");
logger.severe("A severe message.");
}
}
class MyFormatter extends Formatter {
// Create a DateFormat to format the logger timestamp.
private static final DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
public String format(LogRecord record) {
StringBuilder builder = new StringBuilder(1000);
builder.append(df.format(new Date(record.getMillis()))).append(" - ");
builder.append("[").append(record.getSourceClassName()).append(".");
builder.append(record.getSourceMethodName()).append("] - ");
builder.append("[").append(record.getLevel()).append("] - ");
builder.append(formatMessage(record));
builder.append("\n");
return builder.toString();
}
public String getHead(Handler h) {
return super.getHead(h);
}
public String getTail(Handler h) {
return super.getTail(h);
}
}
Below is an output produced by the custom formatter above.
01/05/2009 06:22:09.372 - [org.kodejava.example.util.logging.LogCustomFormatter.main] - [INFO] - Example of creating custom formatter. 01/05/2009 06:22:09.374 - [org.kodejava.example.util.logging.LogCustomFormatter.main] - [WARNING] - A warning message. 01/05/2009 06:22:09.374 - [org.kodejava.example.util.logging.LogCustomFormatter.main] - [SEVERE] - A severe message.
Wayan
Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me, buy me ā or šµ
Latest posts by Wayan (see all)
- How do I set the default Java (JDK) version on Mac OS X? - November 14, 2017
- A User Interface is Like a Joke - November 10, 2017
- How do I pass password to sudo commands? - October 17, 2017
Line 38: you probably meant to append
\n
.Thank you for the correction.
Why did you explicitly create a new
ConsoleHandler
? Why can’t you re-use the handler it has? for example:^ this doesn’t work for me. but I don’t know why. š
I see some bad practices here.
DateFormat
is not thread-safe – useDateTimeFormatter
(Java 8) or create new instance every time you need it (which probabably isn’t too good either š ).Use
System.lineSeparator()
instead of “\n”! You don’t need (and shouldn’t) overridegetHead()
andgetTail()
methods.StringBuilder
can be used in a lot more “streamlined” manner (append().append().apend()
) – you do it, but only partially.Last, but not least, as Rodrigo mentioned, the formatter itself should be in separate class file.
By the way, for case of this example it probably would be good to add handling throwables as well.
Hi Tomasz,
Thanks for the comments to improve the example above.