Log4j2 on Android

前端 未结 2 516
Happy的楠姐
Happy的楠姐 2021-01-05 23:41

I\'m trying to use log4j2 on Android Project (I\'m working on Android Studio).

In order to simplify this question, I will explaine what I\'ve done in a simple dummy

2条回答
  •  隐瞒了意图╮
    2021-01-06 00:08

    Based on your own answer but with simplified code (using Configurator.initialize() instead of XmlConfigurationFactory etc.):

    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import org.apache.logging.log4j.core.LoggerContext;
    import org.apache.logging.log4j.core.config.ConfigurationSource;
    import org.apache.logging.log4j.core.config.Configurator;
    
    // Content of log4j2.xml
    String log4j2xmlFileContent = getLog4j2xmlContent(); 
    
    // convert String into InputStream
    InputStream is = new ByteArrayInputStream(log4j2xmlFileContent.getBytes());
    
    try {
        ConfigurationSource source = new ConfigurationSource(is);
        return Configurator.initialize(null, source);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
    

    Note that:

    • this code must run before the first call of e.g. LogManager.getLogger()
    • the member function Configurator.initialize() is not part of the log4j2 public API (see here)

    See also LOG4J2-952 and Log4jConfigure.java

提交回复
热议问题