java.util.logging.Logger基础教程


     从JDK1.4开始即引入与日志相关的类java.util.logging.Logger,但由于Log4J的存在,一直未能广泛使用。综合网上各类说法,大致认为:

    (1)Logger:适用于小型系统,当日志量过大时性能有待提升。好处在于JDK集成了此类,无需引入新包。且性能也在逐步改善当中,我认为一般而言,使用Logger即可。

     (2)Log4J:并发性较好,性能较强,适用于大型系统。

      本文介绍java.util.logging.Logger的详细用法。


   1、基本概念

     Logger中有2个比较重要的概念,分别是记录器(Logger)与处理器(Handler),二者分别完成以下功能:

    (1)Logger:记录日志,设置日志级别等。

    (2)Handler:确定输出位置等。


  2、Logger相关

(1)一般通过getLogger来获取对象,而不能通过构造函数直接构造。

static Logger getLogger(String name) 
static Logger getLogger(String name, String resourceBundleName) 
Logger objects may be obtained by calls on one of the getLogger factory methods. These will either create a new Logger or return a suitable existing Logger.由于是通过工作获取到的对象,因此,若所传参数相同,则会返回同一个Logger对象。
(2)关于Logger的命名
Logger names can be arbitrary strings, but they should normally be based on the package name or class name of the logged component, such as java.net or javax.swing.
Logger原则上可以任意命名,但实际上一般是与Logger所在包或者所有类的名称相同。
(3)Logger的级别
  • SEVERE(最高值)
  • WARNING
  • INFO
  • CONFIG
  • FINE
  • FINER
  • FINEST(最低值)
此外,还有一个级别 OFF,可用来关闭日志记录,使用级别 ALL 启用所有消息的日志记录。 
logger默认的级别是INFO,比INFO更低的日志将不显示。通过此属性,可以简单的修改Logger的级别,以达到开关日志的目的。
(4)Logger是具有层级关系的,比如org.abc.def会继承org.abc的一些属性。

3、Handler相关
(1)Handler 对象从 Logger 中获取日志信息,并将这些信息导出。例如,它可将这些信息写入控制台或文件中,也可以将这些信息发送到网络日志服务中,或将其转发到操作系统日志中。
(2)可通过执行 setLevel(Level.OFF) 来禁用 Handler,并可通过执行适当级别的 setLevel 来重新启用。
(3)默认情况下,使用ConsoleHandler,即将日志输出至控制台。可通过FileHandler,SocketHandler等,将日志导向其它地方。

4、基本示例
(1)输出至控制台
public  static void main(String[] args) {
		
	final Logger logger = Logger.getLogger("org.jediael.crawl.MyCrawler");
	logger.info("Begin Crawling, Good Luck!");


//为每一个种子url,启动一个线程
	Thread t = new Thread(new Runnable() {
		@Override
		public void run() {
			logger.info(Thread.currentThread()+" start!!");
控制台输出如下:
六月 18, 2014 2:49:35 下午 org.jediael.crawl.MyCrawler main
信息: Begin Crawling, Good Luck!
六月 18, 2014 2:49:35 下午 org.jediael.crawl.MyCrawler$2 run
信息: Thread[Thread-1,5,main] start!!
六月 18, 2014 2:49:35 下午 org.jediael.crawl.MyCrawler$2 run
信息: Thread[Thread-4,5,main] start!!
六月 18, 2014 2:49:35 下午 org.jediael.crawl.MyCrawler$2 run
信息: Thread[Thread-3,5,main] start!!
六月 18, 2014 2:49:35 下午 org.jediael.crawl.MyCrawler$2 run
信息: Thread[Thread-2,5,main] start!!

(2)改变logger的级别
默认情况下,logger的级别为Info,它会处理info及其以上级别的日志;若将其提高至waring,则示例1中的日志将不再显示。
	public  static void main(String[] args) {
		
		final Logger logger = Logger.getLogger("org.jediael.crawl.MyCrawler");
		logger.setLevel(Level.WARNING);
		logger.info("Begin Crawling, Good Luck!");
此时控制台无输出

(3)将日志输出至文件
		final Logger logger = Logger.getLogger("org.jediael.crawl.MyCrawler");
		logger.setLevel(Level.INFO);	
		
		FileHandler fileHandler = new FileHandler("d:\\1.log");
		fileHandler.setLevel(Level.INFO);
		
		logger.addHandler(fileHandler);
		
		logger.info("Begin Crawling, Good Luck!");

此时日志同时输出至控制台及文件中。注意,未指定文件格式的情况下,日志输出格式为XML。
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE log SYSTEM "logger.dtd">
<log>
<record>
  <date>2014-06-18T15:04:44</date>
  <millis>1403075084407</millis>
  <sequence>0</sequence>
  <logger>org.jediael.crawl.MyCrawler</logger>
  <level>INFO</level>
  <class>org.jediael.crawl.MyCrawler</class>
  <method>main</method>
  <thread>1</thread>
  <message>Begin Crawling, Good Luck!</message>
</record>
<record>
  <date>2014-06-18T15:04:44</date>
  <millis>1403075084471</millis>
  <sequence>1</sequence>
若需要改变日志的输出格式,则需要使用Formatter。
如何才能只将日志输出到文件,而不输出至Console?
加上以下语句即可移除console中的输出。
logger.setUseParentHandlers(false);

附API文档说明:
A Logger object is used to log messages for a specific system or application component. Loggers are normally named, using a hierarchical dot-separated namespace. Logger names can be arbitrary strings, but they should normally be based on the package name or class name of the logged component, such as java.net or javax.swing. In addition it is possible to create "anonymous" Loggers that are not stored in the Logger namespace.

Logger objects may be obtained by calls on one of the getLogger factory methods. These will either create a new Logger or return a suitable existing Logger. It is important to note that the Logger returned by one of the getLogger factory methods may be garbage collected at any time if a strong reference to the Logger is not kept.

Logging messages will be forwarded to registered Handler objects, which can forward the messages to a variety of destinations, including consoles, files, OS logs, etc.

Each Logger keeps track of a "parent" Logger, which is its nearest existing ancestor in the Logger namespace.

Each Logger has a "Level" associated with it. This reflects a minimum Level that this logger cares about. If a Logger‘s level is set to null, then its effective level is inherited from its parent, which may in turn obtain it recursively from its parent, and so on up the tree.

The log level can be configured based on the properties from the logging configuration file, as described in the description of the LogManager class. However it may also be dynamically changed by calls on the Logger.setLevel method. If a logger‘s level is changed the change may also affect child loggers, since any child logger that has null as its level will inherit its effective level from its parent.

On each logging call the Logger initially performs a cheap check of the request level (e.g., SEVERE or FINE) against the effective log level of the logger. If the request level is lower than the log level, the logging call returns immediately.

After passing this initial (cheap) test, the Logger will allocate a LogRecord to describe the logging message. It will then call a Filter (if present) to do a more detailed check on whether the record should be published. If that passes it will then publish the LogRecord to its output Handlers. By default, loggers also publish to their parent‘s Handlers, recursively up the tree.

Each Logger may have a ResourceBundle name associated with it. The named bundle will be used for localizing logging messages. If a Logger does not have its own ResourceBundle name, then it will inherit the ResourceBundle name from its parent, recursively up the tree.

Most of the logger output methods take a "msg" argument. This msg argument may be either a raw value or a localization key. During formatting, if the logger has (or inherits) a localization ResourceBundle and if the ResourceBundle has a mapping for the msg string, then the msg string is replaced by the localized value. Otherwise the original msg string is used. Typically, formatters use java.text.MessageFormat style formatting to format parameters, so for example a format string "{0} {1}" would format two parameters as strings.

When mapping ResourceBundle names to ResourceBundles, the Logger will first try to use the Thread‘s ContextClassLoader. If that is null it will try the SystemClassLoader instead. As a temporary transition feature in the initial implementation, if the Logger is unable to locate a ResourceBundle from the ContextClassLoader or SystemClassLoader the Logger will also search up the class stack and use successive calling ClassLoaders to try to locate a ResourceBundle. (This call stack search is to allow containers to transition to using ContextClassLoaders and is likely to be removed in future versions.)

Formatting (including localization) is the responsibility of the output Handler, which will typically call a Formatter.

Note that formatting need not occur synchronously. It may be delayed until a LogRecord is actually written to an external sink.

The logging methods are grouped in five main categories:

  • There are a set of "log" methods that take a log level, a message string, and optionally some parameters to the message string.

  • There are a set of "logp" methods (for "log precise") that are like the "log" methods, but also take an explicit source class name and method name.

  • There are a set of "logrb" method (for "log with resource bundle") that are like the "logp" method, but also take an explicit resource bundle name for use in localizing the log message.

  • There are convenience methods for tracing method entries (the "entering" methods), method returns (the "exiting" methods) and throwing exceptions (the "throwing" methods).

  • Finally, there are a set of convenience methods for use in the very simplest cases, when a developer simply wants to log a simple string at a given log level. These methods are named after the standard Level names ("severe", "warning", "info", etc.) and take a single argument, a message string.

For the methods that do not take an explicit source name and method name, the Logging framework will make a "best effort" to determine which class and method called into the logging method. However, it is important to realize that this automatically inferred information may only be approximate (or may even be quite wrong!). Virtual machines are allowed to do extensive optimizations when JITing and may entirely remove stack frames, making it impossible to reliably locate the calling class and method.

All methods on Logger are multi-thread safe.

Subclassing Information: Note that a LogManager class may provide its own implementation of named Loggers for any point in the namespace. Therefore, any subclasses of Logger (unless they are implemented in conjunction with a new LogManager class) should take care to obtain a Logger instance from the LogManager class and should delegate operations such as "isLoggable" and "log(LogRecord)" to that instance. Note that in order to intercept all logging output, subclasses need only override the log(LogRecord) method. All the other logging methods are implemented as calls on this log(LogRecord) method.










java.util.logging.Logger基础教程,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。