Log4j2 on Android

让人想犯罪 __ 提交于 2019-11-30 21:05:51

I've finally have what I was looking for...

I'm working with Android, and I was unable to recover loggers by name (LogManager.getLogger ("xxx") crashes the App in the worst way possible...)

I think the problem starts when it looks for the log4j2.xml. I put the file everywhere, but it doesn't work... ...so, I wanted to provide the log4j2.xml content into a String...

Here it is what I've done...

    String log4j2xmlFileContent=getLog4j2xmlContent();//Content of my log4j2.xml

    // convert String into InputStream
    InputStream is = new ByteArrayInputStream(log4j2xmlFileContent.getBytes());

    ConfigurationSource source=null;
    try{
        source = new ConfigurationSource(is);
    } catch (IOException ioe){
        ioe.printStackTrace();
    }

    Configuration config = org.apache.logging.log4j.core.config.xml.XmlConfigurationFactory.getInstance().getConfiguration(source);
    loggerContext = (LoggerContext) LogManager.getContext();
    try {
        //loggerContext.stop();
        loggerContext.start(config);
    } catch (Exception e){
        e.printStackTrace();
    }
    return loggerContext;

and now, I can use that loggerContext to get my loggers...

    loggerHitosCarga = context.getLogger("HitosCarga");
    loggerPeticiones = context.getLogger("Peticiones");
    loggerQueries = context.getLogger("Queries");
    loggerDepuracionActual=context.getLogger("DepuracionActual");

    loggerDepuracionActual.warn("FUNCIONAAAAA!!!!..");        
    loggerHitosCarga.info("Loggers inicializados...");

Now I only have to review and improve it a little bit, but it works...

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!