【问题标题】:Alternative for LogManager.setRepositorySelector() from log4j 1.2.17 in log4j 2.16.0log4j 2.16.0 中 log4j 1.2.17 中 LogManager.setRepositorySelector() 的替代方案
【发布时间】:2022-01-19 23:45:10
【问题描述】:

我正在将应用程序从 log4j 1.2.17 转换为 2.16.0,看起来在 log4j2 中 LogManager 中不再有 setRepositorySelector() 方法。我无法按原样使用 log 1.x 桥接器,因为该项目不符合迁移文档中列出的要求。

以下功能是否有任何 log4j2 解决方法?原代码不是我写的,我只是更新一下。

        //The "guard" is a simple object that protects against re-setting of the
        //LoggerFactory by anyone but the one who set it first with a particular
        //"guard".  Basically, this would allow a container to set the LoggerFactory,
        //but disallow applications running in the container from changing it.  If
        //the container holds a handle on the "guard" object, then it alone can
        //change the LoggerFactory.  If no one holds a handle on the "guard" object,
        //then no one can change the LoggerFactory once it is set the first time.       
        Object guard = new Object();
        try {
            LogManager.setRepositorySelector(new ContextJNDISelector(), guard);
        }catch(Exception e){
            System.out.println("Exception, " + CLASS_NAME + ".contextInitialized(): " + e.getMessage());
            //e.printStackTrace();
        }

【问题讨论】:

    标签: java log4j log4j2


    【解决方案1】:

    由于 Log4j 2.x API 可以有多个实现,RepositorySelector 已重命名为 ContextSelector 并移至 Log4jContextFactory。因此你需要使用:

    LogManager.setFactory(new Log4jContextFactory(new JndiContextSelector()));
    

    备注:上述代码必须在任何(直接或间接)调用LogManager.getLogger 或类似方法之前调用。

    【讨论】:

      猜你喜欢
      • 2016-02-28
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      相关资源
      最近更新 更多