从Log4j 1.x到Log4j 2.1.1的迁移问题

时间:2018-08-30 12:31:32

标签: log4j log4j2

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

导入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;
}

1 个答案:

答案 0 :(得分:1)

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();