码迷,mamicode.com
首页 > 编程语言 > 详细

Java Logging: Formatters

时间:2015-06-16 01:20:54      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

 

The Handler‘s in the Java Logging API use a java.util.logging.Formatter to format theLogRecord‘s before writing it to an external system.

Java comes with two built-in Formatter‘s (subclasses of Formatter):

  1. SimpleFormatter
  2. XMLFormatter

The various Handler‘s in the Java Logging API use either of these two Formatter‘s by default, but you can also set your own custom Formatter subclass on a Handler.

You can create your own Formatter by subclassing the java.util.logging.Formatter class. Here is a simple example:

public class MyFormatter extends Formatter {

    @Override
    public String format(LogRecord record) {
        return record.getLevel() + ":" + record.getMessage();
    }
}

The subclass must override the abstract format() method in the Formatter class. The String returned by theformat() is what is forwarded to the external system by the Handler. Exactly how the string should be formatted is up to you.

The Formatter class also contains the convenience method formatMessage() which can be used to format the message using the ResourceBundle of the LogRecord. Here is an example:

public class MyFormatter extends Formatter {

    @Override
    public String format(LogRecord record) {
        return formatMessage(record);
    }
}

You will not often need to implement your own Formatter, but once in a while, if a specific log format is required, a custom Formatter may be useful.

 

Java Logging: Formatters

标签:

原文地址:http://www.cnblogs.com/hephec/p/4579625.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!