log4j 2.16.0 中 log4j 1.2.17 的 LogManager.setRepositorySelector() 替代方案

Alternative for LogManager.setRepositorySelector() from log4j 1.2.17 in log4j 2.16.0

我正在将应用程序从 log4j 1.2.17 转换为 2.16.0,在 log4j2 中,LogManager 中似乎不再有 setRepositorySelector() 方法。我无法按原样使用日志 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();
        }

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

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

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