携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第20天,点击查看活动详情 >> 希望大家可以帮忙点个赞,谢谢!
前言
我们继续看看源码,来一步步去深入Handle,去熟悉那些我们平时用得到和用不到的属性与特点。结合到我们开发工作中,看看我们取用了它哪些好用的地方。
正篇
我们首先继续去从官方注释和属性去看看:
Default constructor. The resulting Handler has a log level of Level.ALL, no Formatter, and no Filter. A default ErrorManager instance is installed as the ErrorManager.
protected Handler() {
}
我们可以直接发现这个是Handle类的默认构造方法,不过注释标明了它的一些属性和特点:生成的 Handler 的日志级别为 Level.ALL,没有 Formatter,也没有 Filter。 默认的 ErrorManager 实例部署实现为 ErrorManager。 接下来publish方法:
/**
* Publish a <tt>LogRecord</tt>.
* <p>
* The logging request was made initially to a <tt>Logger</tt> object,
* which initialized the <tt>LogRecord</tt> and forwarded it here.
* <p>
* The <tt>Handler</tt> is responsible for formatting the message, when and
* if necessary. The formatting should include localization.
*
* @param record description of the log event. A null record is
* silently ignored and is not published
*/
public abstract void publish(LogRecord record);
根据注释来看,这个方法是用来发布一个日志记录的,原理是日志记录请求最初是对 Logger 对象发出的,将该对象初始化为 LogRecord 并将其转发到此处。需要注意的是Handle负责在必要时对消息进行格式化。 格式应包括本地化。而这个方法的参数要求是:这是一个日志事件的描述,如果是空记录则被静默忽略且不发布。
接着是flush方法:
/**
* Flush any buffered output.
*/
public abstract void flush();
注释是说这个方法可以刷新任何缓冲的输出。所以应该是一个刷新缓冲的方法。 然后还有close方法:
/**
* Close the <tt>Handler</tt> and free all associated resources.
* <p>
* The close method will perform a <tt>flush</tt> and then close the
* <tt>Handler</tt>. After close has been called this <tt>Handler</tt>
* should no longer be used. Method calls may either be silently
* ignored or may throw runtime exceptions.
*
* @exception SecurityException if a security manager exists and if
* the caller does not have <tt>LoggingPermission("control")</tt>.
*/
public abstract void close() throws SecurityException;
这是用来关闭 Handler 并释放所有相关资源的方法。close 方法会执行刷新,然后结束Handler。 调用 close() 后,不应再使用Handle类再处理其他活动。 方法调用可能会被静默忽略,也可能会引发运行时异常,抛出异常为SecurityException(如果存在安全管理器并且调用者没有用 LoggingPermission("control"))。
(未完待续)