Log4j 1.x到Log4j 2.1.1迁移问题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Log4j 1.x到Log4j 2.1.1迁移问题相关的知识,希望对你有一定的参考价值。

我正在尝试将代码迁移到版本2.但是,我遇到了一些问题,在log4j 2.1.1中找到了getCurrentLoggers的替代方法

import org.apache.logging.log4j.LogManager.getCurrentLoggers();不存在。

    private ArrayList<LoggerName> getLoggerList() {

    // Generate a list of all the loggers and levels
    ArrayList<String> al = new ArrayList<String>();
    HashMap<Object, Object> hm = new HashMap<Object, Object>();
    ArrayList<LoggerName> list = new ArrayList<LoggerName>();

    // Get RootLogger
    Logger rootLogger = LogManager.getRootLogger();
    String rootLoggerName = rootLogger.getName();
    al.add(rootLoggerName);
    hm.put(rootLoggerName, rootLogger);

    // All Other Loggers ISSUE HERE

    Enumeration e = LogManager.getCurrentLoggers();

    while (e.hasMoreElements()) {               
        Logger t1Logger = (Logger) e.nextElement();
        String loggerName = t1Logger.getName();
        al.add(loggerName);
        hm.put(loggerName, t1Logger);       
    }

    String[] alLoggerStr = ((String[]) al.toArray(new String[0]));
    Arrays.sort(alLoggerStr);
    for (int i=0; i < alLoggerStr.length; i++) { 
        Logger logger = (Logger) hm.get(alLoggerStr[i]);

        String name = logger.getName();
        String level = logger.getLevel().toString();
        String parent = GenFuncs.EMPTY_STRING;
        if (logger.getParent() != null) {
            parent = (logger.getParent().getName();
        }
        LoggerName logData = new LoggerNameImpl(name, parent, level);

        list.add(logData);
    }
    return list;
}
答案

Stack Overflow找到答案

File configFile = new File("c:\my_path\log4j2.xml");
LoggerContext loggerContext = Configurator.initialize("my_config", null, configFile.toURI());
Configuration configuration = loggerContext.getConfiguration();
Collection<LoggerConfig> loggerConfigs = configuration.getLoggers().values();

以上是关于Log4j 1.x到Log4j 2.1.1迁移问题的主要内容,如果未能解决你的问题,请参考以下文章

log4j 2 迁移桥 log4j-1.2-api.jar 缺少类

将 log4j 1.2.x 迁移到 log4j 2.16.0

将 log4j.properties 文件从 Log4j 版本 1 迁移到 2 的合适指南

从 log4j 1.2.17 迁移后的 log4j 2.2 问题

从 log4j 迁移到 logback

将项目从 log4j 迁移到 slf4j+log4j