Java Logging: Formatters

本文介绍如何在Java中使用日志记录器,包括内置的SimpleFormatter和XMLFormatter,以及如何创建和使用自定义日志记录器。通过提供一个简单的示例,解释了如何覆盖Formatter类的方法来定制日志输出格式,并讨论了自定义日志格式的潜在应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

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.

 

转载于:https://www.cnblogs.com/hephec/p/4579625.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值