关于log4j

本文详细解析了Log4j在源码中如何通过静态代码块指定配置文件log4j.properties的加载过程,包括默认初始化覆盖、资源搜索策略及配置委托等关键步骤。

说明:因为导入了log4gjar包文件,在源码中有一段静态代码块,中标识了log4j的加载路径就在根目录下进行导入.并且名称为log4j.properties.

 

Log4j加载

static public final String DEFAULT_CONFIGURATION_FILE = "log4j.properties";

 

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.");

        try {

            OptionConverter.selectAndConfigure(url, configuratorClassName,

                  LogManager.getLoggerRepository());

        } catch (NoClassDefFoundError e) {

            LogLog.warn("Error during default initialization", e);

        }

      } else {

       LogLog.debug("Could not find resource: ["+configurationOptionStr+"].");

      }

    } else {

        LogLog.debug("Default initialization of overridden by " +

            DEFAULT_INIT_OVERRIDE_KEY + "property.");

    } 

  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值