java.util.logging是JDK自带的日志包,可以将日志输出到文件、内存或者控制台,作用与我们常用的log4j类似。
包中的Handler类和Formatter类在设计上利用了桥接模式,首先看类关系图:
Handle和Formatter类是两个抽象类,它们可以分别独立的变化(有不同的子类);而Handle类中包含对Formatter类的引用。
//handle类中的set方法
public synchronized void setFormatter(Formatter newFormatter) throws SecurityException {
checkPermission();
// Check for a null pointer:
newFormatter.getClass();
formatter = newFormatter;
}
Handle通过setFormatter方法可以方便的替换不同的Formatter类。
Handle与Formatter介绍
1、Handle.
来自JDK本身的介绍:
/**
* A <tt>Handler</tt> object takes log messages from a <tt>Logger</tt> and
* exports them. It might for example, write them to a console
* or write them to a file, or send them to a network logging service,
* or forward them to an OS log, or whatever.
* <p>
* A <tt>Handler</tt> can be disabled by doing a <tt>setLevel(Level.OFF)</tt>
* and can be re-enabled by doing a <tt>setLevel</tt> with an appropriate level.
* <p>
* <tt>Handler</tt> classes typically use <tt>LogManager</tt> properties to set
* default values for the <tt>Handler</tt>'s <tt>Filter</tt>, <tt>Formatter</tt>,
* and <tt>Level</tt>. See the specific documentation for each concrete
* <tt>Handler</tt> class.
*
*
* @since 1.4
*/
handle对象可以从一个logger中取出信息并输出到控制台、文件或者调用其它api发送到网络中;
handle可以通过setLevel方法关闭或打开;
handle通常是利用LogManager去设置自身的Handler、Filter、Formatter等属性值。
*备注:虽然父类Handle中提供了setFormatter方法,但子类streamhandle中也重新提供了配置各个成员变量值的方法:
private void configure() {
LogManager manager = LogManager.getLogManager();
String cname = getClass().getName();
setLevel(manager.getLevelProperty(cname +".level", Level.INFO));
setFilter(manager.getFilterProperty(cname +".filter", null));
setFormatter(manager.getFormatterProperty(cname +".formatter", new SimpleFormatter()));
try {
setEncoding(manager.getStringProperty(cname +".encoding", null));
} catch (Exception ex) {
try {
setEncoding(null);
} catch (Exception ex2) {
// doing a setEncoding with null should always work.
// assert false;
}
}
}
2、Formatter
JDK的介绍:
/**
* A Formatter provides support for formatting LogRecords.
* <p>
* Typically each logging Handler will have a Formatter associated
* with it. The Formatter takes a LogRecord and converts it to
* a string.
* <p>
* Some formatters (such as the XMLFormatter) need to wrap head
* and tail strings around a set of formatted records. The getHeader
* and getTail methods can be used to obtain these strings.
*
* @since 1.4
*/
Formatter支持格式化日志数据;通常每个Handler中都会有一个Formatter引用,Formatter可以将LogRecord对象转换为一个string字符串。