`
DavyJones2010
  • 浏览: 151893 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Java Logging Techniques Summary(JUL in Depth)

阅读更多

1. JUL is an inbeded util tool for logging.

 

2. The work flow of JUL



3. JUL has abstracted Logging procession into the interaction of several Classes.

    1) Level --> Define the the severe level of the log. 

                  --> JUL has used a different logging level compared with Log4j.

                  -->  1) SEVERE

                         2) WARNING

                         3) INFO

                         4) CONFIG

                         5) FINE

                         6) FINER

                         7) FINEST

                         In addition to that, you have also the levels OFF and ALL to turn the logging of or to log everything.

     2) LogRecord --> Encapsulated a record that to be printed.

                           --> It contains following information:

                           1) Level (The level of this record)

                           2) sequenceNumber (Every time a record is created, sequenceNumber increased by 1)

                           3) sourceClassName (The class where this record is printed)

                           4) sourceMethodName (The method where this record in printed)

                           5) message (The message itself)

                           6) ...

    3) Formatter --> It a formatter that is used to format a LogRecord.

                        --> JUL provides two kinds of Formatter: SimpleFormatter(Default) & XMLFormatter

                        --> SimpleFormatter is used by default. It prints record information as the following format:

                           --> Date + Time + LoggerName/sourceClassName + methodName

                           --> Level + Message

                           --> Exception Info

May 21, 2013 2:35:30 PM edu.xmu.logging.Logging_JDKLogging.AppTest loggerTest
INFO: Main running

                      --> XMLFormatter is not often used. As the format of below:

                           --><record></record>                         

    4) Handler  --> The position where the record to be printed.

                       --> The hierarchy of Handlers is as below:

 

                     --> The Handler contains a reference to Formatter, Level, Filter

                          --> The reference of Formatter is used to format the LogRecord into String.

                          --> The reference of Level is used to define the Level supported by this Handler

                          --> The Filter?...

                     --> The function publish() in Handler is the real function that realize the print LogRecord function.

     5) LogManager  --> An singleton instance that is used to read the configuration file.

                               --> Maintains a map of Logger instance.

                                  -->  When instantiating the LogManager, user can use java.util.logging.manager to point out the custom LogManager.

                                         If we do not point out, then it will use LogManager by default.

                                         After Instantiation, a RootLogger is created and put in the logMap in LogManager.

                                  --> About the logMap in the LogManager

    // Table of known loggers.  Maps names to Loggers.
    private Hashtable<String,Logger> loggers = new Hashtable<String,Logger>();
                                 --> The loggers is organized as the format of Tree:  edu<--xmu<--logging. So the if we getLogger("edu.xmu.logging.LoggingTest"), manager will find in this tree/map, when cannot find this, then it will try to find as getLogger("edu.xmu.logging"), and if cannot find, then will getLogger("edu.xmu") ... So as the level organized.

                                 --> But the LogManager will allow us to control things at more than just the class level. We could set the logging level for a package, or even a set of packages, by calling the LogManager.setLevel(String name, Level level) method.                                                                 So, for example, we could set the logging level of all loggers for this article to Level.FINE by making this call:

 

LogManager.getLogManager().setLevel("logging", Level.FINE);

 

                                      This would make every Logger with the package prefix of "logging" have a level of Level.FINE, unless that particular Logger already had a Level explicitly set:

Diagram.

                                      We would still need to turn up the levels of the root handlers as before, but would not have to set the individual loggers one at a time.
                                 --> As the name of RootLogger is "", all the configuration for RootLogger is started with "."

     6) Logger  --> The interfact that user used to print log.

                      -->  It contains "name、Handlers、resourceBundleName、useParentHandlers、filter、anonymous、levelObject、parent、kids" fields.

                         -->  It provides getLogger() interface. When user passes into a name, then it returns a Logger instance.  

    public static synchronized Logger getLogger(String name) {
	LogManager manager = LogManager.getLogManager();
	Logger result = manager.getLogger(name);
	if (result == null) {
	    result = new Logger(name, null);
	    manager.addLogger(result);
	    result = manager.getLogger(name);
	}
	return result;
    }

 

4. Several ways to config Logger [Reference to DLevin]

     1) 对Logger的配置支持一下几种方式:  

         <name>.level=INFO|CONFIG….             

         handers=<handlerName1>,<handlerName2>…. (以”,”分隔或以空格、TAB等字符分隔,全局Handler)       

         config=<configClassName1>,<configClassName2>….(自定义类,实现在其构造函数中实现自定义配置)

         <name>.userParentHandlers=true|false|1|0

         <name>.handlers=<handlerName1>,<handlerName2>…(以”,”分隔或以空格、TAB等字符分隔)

         <handlerName>.level=INFO|CONFIG….

        以及各自Handler本身支持的配置,具体各自的Handler。

     2) 用户可以通过以下方式自定义配置文件:

     a. 设置系统属性java.util.logging.config.class,由自定义类的构造函数实现自定义配置,如调用LogManager、Logger中的一些静态方法。

     b.设置系统属性java.util.logging.config.file,自定义配置文件路径。读取该文件中的内容作为配置信息。

     c. 默认使用${java.home}/lib/logging.properties文件作为配置文件(JDK已经提供了一些默认配置,一般是${JRE_HOME}/lib/logging.properties文件)

5. A simple exmple for configuration JUL

    In the path of ${JRE_HOME}/lib/logging.properties

############################################################
#  	Default Logging Configuration File
#
# You can use a different file by specifying a filename
# with the java.util.logging.config.file system property.  
# For example java -Djava.util.logging.config.file=myfile
############################################################

############################################################
#  	Global properties
############################################################

# "handlers" specifies a comma separated list of log Handler 
# classes.  These handlers will be installed during VM startup.
# Note that these classes must be on the system classpath.
# By default we only configure a ConsoleHandler, which will only
# show messages at the INFO and above levels.
handlers= java.util.logging.ConsoleHandler

# To also add the FileHandler, use the following line instead.
#handlers= java.util.logging.FileHandler, java.util.logging.ConsoleHandler

# Default global logging level.
# This specifies which kinds of events are logged across
# all loggers.  For any given facility this global level
# can be overriden by a facility specific level
# Note that the ConsoleHandler also has a separate level
# setting to limit messages printed to the console.
.level= INFO

############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################

# default file output is in user's home directory.
java.util.logging.FileHandler.pattern = %h/java%u.log
java.util.logging.FileHandler.limit = 50000
java.util.logging.FileHandler.count = 1
java.util.logging.FileHandler.formatter = java.util.logging.XMLFormatter

# Limit the message that are printed on the console to INFO and above.
java.util.logging.ConsoleHandler.level = INFO
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter


############################################################
# Facility specific properties.
# Provides extra control for each logger.
############################################################

# For example, set the com.xyz.foo logger to only log SEVERE
# messages:
edu.xmu.logging.Logging_JDKLogging.level = ALL

   Comments:

       1) Here we can see that the default handler is ConsoleHandler. So if we didn't change this, by default, the information will be printed in console.

       2) Here we can see that the default level for RootLogger is INFO. So if we didn't change this, by default, the information at levels that is lower than INFO will not be printted.

       3) The default level for ConsoleHander is INFO.

       4) The default formatter is SimpleFormatter. So the output information will be printed as the format specified by SimpleFormatter.  

 

6. A simple example for using JUL

    1. Test Class

package edu.xmu.logging.Logging_JDKLogging;

import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

import org.junit.Before;
import org.junit.Test;

/**
 * Unit test for simple App.
 */
public class AppTest
{
	private static Logger logger = null;
	private static SimpleFormatter fileFormatter = null;
	private static FileHandler fileHandler = null;

	@Before
	public void setUp() throws SecurityException, IOException
	{
		logger = Logger.getLogger(AppTest.class.getName());

		fileFormatter = new SimpleFormatter();
		fileHandler = new FileHandler("Logging.txt");
		fileHandler.setFormatter(fileFormatter);
		fileHandler.setLevel(Level.ALL);

		logger.addHandler(fileHandler);
		logger.setLevel(Level.FINE);
	}

	@Test
	public void loggerTest()
	{
		logger.severe("Severe Logging");
		logger.warning("Warning Logging");
		logger.info("Info Logging");
		logger.config("Config Logging");
		logger.fine("Fine Logging");
		logger.finer("Finner Logging");
		logger.finest("Finest Logging");
	}
}

   2. Console output

May 23, 2013 6:22:54 PM edu.xmu.logging.Logging_JDKLogging.AppTest loggerTest
SEVERE: Severe Logging
May 23, 2013 6:22:54 PM edu.xmu.logging.Logging_JDKLogging.AppTest loggerTest
WARNING: Warning Logging
May 23, 2013 6:22:54 PM edu.xmu.logging.Logging_JDKLogging.AppTest loggerTest
INFO: Info Logging

    3. File output (Logging.txt)

May 23, 2013 6:22:54 PM edu.xmu.logging.Logging_JDKLogging.AppTest loggerTest
SEVERE: Severe Logging
May 23, 2013 6:22:54 PM edu.xmu.logging.Logging_JDKLogging.AppTest loggerTest
WARNING: Warning Logging
May 23, 2013 6:22:54 PM edu.xmu.logging.Logging_JDKLogging.AppTest loggerTest
INFO: Info Logging
May 23, 2013 6:22:54 PM edu.xmu.logging.Logging_JDKLogging.AppTest loggerTest
CONFIG: Config Logging
May 23, 2013 6:22:54 PM edu.xmu.logging.Logging_JDKLogging.AppTest loggerTest
FINE: Fine Logging

    1) Q: Why does the console output?

        A: Because the FileHandler is configured in ${JRE_HOME}/lib/logging.properties files. And this FileHandler is ConsoleHander and is the parent of all applications.

        X: We can add a sentence like below: Then the console output will gone.

logger.setUseParentHandlers(false);

    2) Q: Why does we only have the ConsoleOutput has only three items and fileOutput has five output items?

        A: Because in the configuration file(Refer Below).

java.util.logging.ConsoleHandler.level = INFO

    3) Q: What's the relationship of level in Handler and in Logger?

        A:  We can regard the relationship of them as below figure:<Think LogRecord as water that flows through the two pieces of pie>


    4) Q: How can we make different configuration files for different application/modules instead of configure in code/jre-global-configuration-file? 
        A: This configuration file need to be pass to your application using java -Djava.util.logging.config.file option

 

Reference Links:

    1) http://www.blogjava.net/DLevin/archive/2012/11/08/390992.html

    2) http://www.onjava.com/pub/a/onjava/2002/06/19/log.html?page=2

    3) http://tutorialswithexamples.com/java-logging-configuration-using-properties-file/

 

  • 大小: 32.4 KB
  • 大小: 1.5 KB
  • 大小: 3.8 KB
  • 大小: 14.4 KB
分享到:
评论

相关推荐

    java logging

    Java日志记录(Java Logging)是Java开发中的一个重要组成部分,主要用于收集、管理和处理应用程序的运行时信息。在Java中,日志系统可以帮助开发者追踪错误、调试代码、监控系统性能以及记录用户活动,对于理解和...

    java.util.logging.Logger使用详解

    ### Java.util.logging.Logger 使用详解 #### 一、创建Logger对象 在Java中,`java.util.logging.Logger` 是标准的日志框架之一,它提供了基础的日志记录功能。为了使用这一功能,首先需要获得 `java.util.logging...

    Java Logger Logging 封装

    `Logger`是Java标准库`java.util.logging`包提供的日志工具,它提供了多种级别的日志记录,如`SEVERE`、`WARNING`、`INFO`、`CONFIG`、`FINE`、`FINER`和`FINEST`。本篇文章将深入探讨Java中的`Logger`封装,以及...

    APRESS--Logging-in-Java-with-the-JDK-1_4-Logging-API-and-Apache-log4j

    APRESS--Logging-in-Java-with-the-JDK-1_4-Logging-API-and-Apache-log4j

    Optimizing Java: Practical Techniques for Improving JVM Application Performance

    Pub Date: 2018 Learn how Java principles ...Explore JIT compilation and Java language performance techniques Learn performance aspects of the Java Collections API and get an overview of Java concurrency

    How is logging implemented in OSS?

    Method: In this paper, we carried out an empirical study to explore the logging practice in open source software projects so as to establish a basic understanding on how logging practice is applied ...

    Java LoggingAPI 使用方法

     Log4j中是通过log4j.properties这个配置文件控制日志的输出,java logging中是通过logging.properties文件完成类似的功能。  Logging.properties文件位于JDK安装路径的 jre/lib/目录下,直接上配置文件: ...

    WELL logging depth correction

    ### WELL Logging Depth Correction 在石油勘探与开发领域中,井眼测井(WELL logging)是一种重要的技术手段,用于获取地层的各种物理性质参数。而深度校正则是保证测井数据准确性的重要步骤之一。本文将从给定...

    commons-logging-1.2

    Commons Logging 是 Apache 组织提供的一款轻量级的日志记录工具库,它的主要目标是为 Java 开发者提供一个简单的接口来使用各种日志框架,如 Log4j、Java Util Logging(JUL)或者 Simple Logging Facade for Java...

    java中logging的demo

    在Java编程语言中,日志(Logging)是一个关键的组件,用于记录应用程序的运行时信息。日志可以帮助开发者追踪程序的执行过程,诊断错误,优化性能,并为用户提供有关系统活动的详细信息。Java中的日志框架包括内置...

    commons-logging-1.2_commonslogging_

    这个接口能够适配多种流行的日志实现,如Log4j、java.util.logging(JUL)和Logback等。在标题"commons-logging-1.2_commonslogging_"中提到的"commons-logging-1.2.jar"就是这个库的1.2版本,它是Spring框架中常用...

    JUL的简单日志实现

    **Java Util Logging (JUL) 简单日志实现** Java Util Logging(JUL)是Java标准库中内置的日志框架,它提供了一个灵活的日志系统,允许开发者记录应用程序中的各种信息。JUL的设计目的是为了满足不同级别的日志...

    commons-logging.jar

    commons-logging-java1.1.jar, commons-logging-optional.jar, commons-logging-osgi-1.0.jar, commons-logging-osgi.jar, commons-logging-REDUCED.jar, commons-logging-tests.jar, commons-logging_1.0.3.jar, ...

    commons-logging-1.2.rar

    Commons Logging 是 Apache 软件基金会的一个项目,它允许开发者在不改变代码的情况下切换到不同的日志框架,如 Log4j、Java Util Logging (JUL) 或者 logback。 描述 "commons-logging-1.2.rar" 提供的信息有限,...

    Log4j与common-logging

    而common-logging则是Apache Commons的一个组件,它提供了一个统一的日志接口,允许开发者在不修改代码的情况下切换底层的日志实现,比如从Log4j切换到java.util.logging(JUL)。 **Log4j** Log4j是Java日志领域的...

    log4j-jul-2.12.1-API文档-中英对照版.zip

    标签:apache、logging、log4j、jul、中英对照文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码和结构保持不变,注释和说明精准...

    java.lang.NoClassDefFoundError: org/jboss/logging/

    Java编程中的`java.lang.NoClassDefFoundError: org/jboss/logging/`是一个常见的运行时错误,通常发生在尝试执行一个类时,JVM无法找到在编译时已经存在的类定义。这个错误并不意味着类在编译期间不存在,而是表明...

    java 开发工具:commons-logging.jar(spring必备包)

    java 开发工具:commons-logging.jar(spring必备包)

    commons-logging-1.1.1.jar和java-unrar-0.3.jar

    总之,"java-unrar-0.3.jar"和"commons-logging-1.1.1.jar"为Java开发者提供了处理RAR文件的强大工具,使得在Java环境中解压RAR文件变得简单易行,同时通过Commons Logging提供了灵活的日志记录机制。在项目中正确...

Global site tag (gtag.js) - Google Analytics