`
tanghongjun1985
  • 浏览: 55180 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Log4J源码分析(三)

阅读更多
转载:http://jmut.bokee.com/

上回说到LogManager,接下来就分析它。
先看它的注释:

/**
* Use the LogManager class to retreive {@link Logger}
* instances or to operate on the current {@link
* LoggerRepository}. When the LogManager class is loaded
* into memory the default initalzation procedure is inititated. The
* default intialization procedure is described in the
* href="../../../../manual.html#defaultInit">short log4j manual.
*
* @author Ceki Gülcü */
可见这个类可能是负责全局Logger管理。这个类不大,但感觉它是很重要的一个类,所以有必要深入研究一下。既然在注释中提到了手册中有关于默认初始化过程的描述,那就先看看它是怎么说的。
The exact default initialization algorithm is defined as follows:

Setting the log4j.defaultInitOverride system property to any other value then "false" will cause log4j to skip the default initialization procedure (this procedure).
Set the resource string variable to the value of the log4j.configuration system property. The preferred way to specify the default initialization file is through the log4j.configuration system property. In case the system property log4j.configuration is not defined, then set the string variable resource to its default value "log4j.properties".
Attempt to convert the resource variable to a URL.
If the resource variable cannot be converted to a URL, for example due to a MalformedURLException, then search for the resource from the classpath by calling org.apache.log4j.helpers.Loader.getResource(resource, Logger.class) which returns a URL. Note that the string "log4j.properties" constitutes a malformed URL.
See

Loader.getResource(java.lang.String) for the list of searched locations.
If no URL could not be found, abort default initialization. Otherwise, configure log4j from the URL.
The PropertyConfigurator will be used to parse the URL to configure log4j unless the URL ends with the ".xml" extension, in which case the DOMConfigurator will be used. You can optionaly specify a custom configurator. The value of the log4j.configuratorClass system property is taken as the fully qualified class name of your custom configurator. The custom configurator you specify must implement the Configurator interface.

以上是就是整个初始化过程。其源码如下:
static {
// By default we use a DefaultRepositorySelector which always returns 'h'.
Hierarchy h = new Hierarchy(new RootLogger((Level) Level.DEBUG));
repositorySelector = new DefaultRepositorySelector(h);

/** Search for the properties file log4j.properties in the CLASSPATH. */
String override =OptionConverter.getSystemProperty(DEFAULT_INIT_OVERRIDE_KEY,
null);

// if there is no default init override, then get the resource
// specified by the user or the default config file.
if(override == null || "false".equalsIgnoreCase(override)) {

String configurationOptionStr = OptionConverter.getSystemProperty(
DEFAULT_CONFIGURATION_KEY,
null);

String configuratorClassName = OptionConverter.getSystemProperty(
CONFIGURATOR_CLASS_KEY,
null);

URL url = null;

// if the user has not specified the log4j.configuration
// property, we search first for the file "log4j.xml" and then
// "log4j.properties"
if(configurationOptionStr == null) {
url = Loader.getResource(DEFAULT_XML_CONFIGURATION_FILE);
if(url == null) {
url = Loader.getResource(DEFAULT_CONFIGURATION_FILE);
}
} else {
try {
url = new URL(configurationOptionStr);
} catch (MalformedURLException ex) {
// so, resource is not a URL:
// attempt to get the resource from the class path
url = Loader.getResource(configurationOptionStr);
}
}

// If we have a non-null url, then delegate the rest of the
// configuration to the OptionConverter.selectAndConfigure
// method.
if(url != null) {
LogLog.debug("Using URL ["+url+"] for automatic log4j configuration.");
OptionConverter.selectAndConfigure(url, configuratorClassName,
LogManager.getLoggerRepository());
} else {
LogLog.debug("Could not find resource: ["+configurationOptionStr+"].");
}
}
1、检查log4j.defaultInitOverride系统变量的值,false将跳过默认初始化过程。

2、读取log4j.configuration系统变量的值,生成配置文件url,默认值为log4j.properties或者log4j.xml。
// if the user has not specified the log4j.configuration
// property, we search first for the file "log4j.xml" and then
// "log4j.properties"
if(configurationOptionStr == null) {
 url = Loader.getResource(DEFAULT_XML_CONFIGURATION_FILE);
 if(url == null) {
 url = Loader.getResource(DEFAULT_CONFIGURATION_FILE);
 }
} else {
 try {
  url = new URL(configurationOptionStr);
 } catch (MalformedURLException ex) {
 // so, resource is not a URL:
 // attempt to get the resource from the class path
 url = Loader.getResource(configurationOptionStr);
 }
}
3、如果url存在,则继续用OptionConverter初始化。
// If we have a non-null url, then delegate the rest of the
// configuration to the OptionConverter.selectAndConfigure
// method.
if(url != null) {
 LogLog.debug("Using URL ["+url+"] for automatic log4j configuration.");
 OptionConverter.selectAndConfigure(url, configuratorClassName,
 LogManager.getLoggerRepository());
} else {
 LogLog.debug("Could not find resource: ["+configurationOptionStr+"].");
}
我们又发现了三个重要角色 Hierarchy、OptionConverter和Loader。我们先说OptionConverter,显然它是一个工具类,提供一些基础服务。我们现在用到的方法是:
/**
Configure log4j given a URL.
The url must point to a file or resource which will be interpreted by
a new instance of a log4j configurator.
All configurations steps are taken on the hierarchy passed as a parameter.

@param url The location of the configuration file or resource.
@param clazz The classname, of the log4j configurator which will parse
the file or resource at url. This must be a subclass of
{@link Configurator}, or null. If this value is null then a default
configurator of {@link PropertyConfigurator} is used, unless the
filename pointed to by url ends in '.xml', in which case
{@link org.apache.log4j.xml.DOMConfigurator} is used.
@param hierarchy The {@link org.apache.log4j.Hierarchy} to act on.

@since 1.1.4 */

static
public
void selectAndConfigure(URL url, String clazz, LoggerRepository hierarchy) {
 Configurator configurator = null;
 String filename = url.getFile();

 if(clazz == null && filename != null && filename.endsWith(".xml")) {
  clazz = "org.apache.log4j.xml.DOMConfigurator";
 }

 if(clazz != null) {
  LogLog.debug("Preferred configurator class: " + clazz);
  configurator = (Configurator) instantiateByClassName(clazz,
  Configurator.class,null);
  if(configurator == null) {
   LogLog.error("Could not instantiate configurator ["+clazz+"].");
   return;
  }
 } else {
  configurator = new PropertyConfigurator();
 }

 configurator.doConfigure(url, hierarchy);
}
该方法先构造正确的Configurator,再进行配置。有两个默认的Configurator,一个是DOMConfigurator,一个是PropertyConfigurator是。在没有指定Configurator时,如果配置文件是以.xml结尾,则使用DOMConfigurator,否则使用PropertyConfigurator。
分享到:
评论

相关推荐

    Log4j2效率测试源码

    Log4j2效率测试源码

    log4j返序列化源码分析

    log4j返序列化源码分析

    log4j 介绍

    log4j 介绍 log4j 1.x 源码分析 logback log4j2介绍

    Log4j2异步写日志源码

    分三类文件,pom通过maven构建所需jar包,log4j2.xml配置文件,TestController.java测试类,使用debug测试效果较明显。

    log4j详解与实战

    深入的介绍log4j的各种使用方法,不容错过

    apache-log4j-2.4-src.zip源码

    apache-log4j-2.4-src.zip 源码加入,就可以看到log4j内部的源码了

    Struts2 日志原理及配置方法(结合Log4j)

    NULL 博文链接:https://adrain-work-163-com.iteye.com/blog/1545091

    log4c源代码

    log4c的源代码。log4c是用C语言编写的日志工具,借鉴了log4j的思想,可以自由配置日志的输出格式、输出文件等,是一个很方便的程序调试、运行追踪工具。还有一个C语言的日志工具是ZLog,与这个有些像。

    Struts-menu源码分析

    优秀而且实用的代码有很多,比如Junit,比如Jive,比如petStore,甚至是tomcat的Example、Log4j的Example。 一段广告完毕,下面就为大家分析一下struts-menu的源码,作为送给大家的圣诞礼物吧。Struts-Menu也来自一...

    slf4j使用和源码分析

    slf4j使用 SLF4J 是为各种 loging APIs 提供一个简单统一的接口,从而使得最终用户能够在部署的时候配置自己希望的...也可以通过 SLF4J 提供的 API 实现来开发相应的适配器如 Log4jLoggerAdapter、JDK14LoggerAdapter。

    java版ss源码-ErRabbit:使用Log4j的远程日志控制台服务器。可视化异常堆栈跟踪日志视图

    Log4j、slf4j(by Plinio Freire) 和 ActiveMQ 收集将使其与其他程序轻松兼容。 介绍幻灯片 有什么区别。 RrRabbit 旨在可视化错误日志 易于集成到现有的 Java 应用程序上。 한국어 설명은 에 있습니다。 结构 Web ...

    spring mvc项目

    spring mvc maven项目,导入IDEA后无报错,需要在IDEA中...该项目使用servlet3.0规范,无web.xml,无spring.xml等配置文件,所有的配置均通过Java Config、注解搞定,项目中还集成了log4j2技术,以及前端html文件等。

    java8集合源码分析-spider-tangpoem:优雅的使用轻量级爬虫框架WebMagic

    java8 集合源码分析 spider-tangpoem项目 优雅的使用WebMagic框架,爬取唐诗别苑网的诗人诗歌数据 ...日志log4j 1.7.25 Java反射 单例模式、工厂模式、代理模式 项目结构 biz包:包括页面爬取逻辑的

    Spring Boot实战与原理分析视频课程包含14-18

    --演示了如何在Spring Boot里面使用日志配置,以及logback,log4j2等日志的使用 23 Spring Boot 监控和度量47:09 --Spring Boot内置的监控点、自定义的监控状况检查、自定义度量统计,输出等等 24 Spring Boot ...

    日志集群分析器hblog.zip

    支持的体制格式有:Syslog、 Log4j、Java GC log。具有以下功能:Remote access to logs via a single CLIMulti-host summaries of log line frequenciesMulti-host realtime tailing (like tail -f) 标签:...

    北风客户关系管理源码 CRM

    4.日程/任务管理(包括日志之类的Log4J、JUnit技术) 5.项目管理 6.数据字典 .......................................................................... 六、课程特色 1真实性、实战性 如果您能够完整的学好这个...

    《程序天下:J2EE整合详解与典型案例》光盘源码

    6.2 建立Log4j的开发环境 6.2.1 下载Log4j 6.2.2 配置Log4j 6.3 Log4j的使用方法 6.3.1 配置Log4j 6.3.2 配置根Logger 6.3.3 指定日志输出位置 6.3.4 指定日志输出格式 6.3.5 指定日志输出优先级 6.3.6 在代码中使用...

    Java进销存ERP管理系统源码

    日志管理:Log4j 2.10.0 JS框架:Jquery 1.8.0 UI框架: EasyUI 1.3.5 模板框架: AdminLTE 2.4.0 项目管理框架: Maven 3.2.3 开发环境: IDE: IntelliJ IDEA 2017+ eclipse DB: Mysql5.7.4 JDK: JDK1.8 Maven: Maven...

    搞定J2EE:STRUTS+SPRING+HIBERNATE整合详解与典型案例 (2)

    一共四个,其中pdf 三个包,源码一个包 第一章 J2EE快速入门 1.1 J2EE概述 1.1.1 J2EE的来源 1.1.2 J2EE整体框架 1.1.3 从J2EE到JavaEE 1.2 J2EE组件 1.2.1 客户端组件 1.2.2 Web组件 1.2.3 业务逻辑组件 1.3 J2EE...

Global site tag (gtag.js) - Google Analytics