Skip to content Skip to sidebar Skip to footer

Log4j2 On Android

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 project (I got the

Solution 1:

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...

Solution 2:

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.xmlStringlog4j2xmlFileContent= getLog4j2xmlContent(); 

// convert String into InputStreamInputStreamis=newByteArrayInputStream(log4j2xmlFileContent.getBytes());

try {
    ConfigurationSourcesource=newConfigurationSource(is);
    return Configurator.initialize(null, source);
} catch (IOException e) {
    e.printStackTrace();
}
returnnull;

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

Post a Comment for "Log4j2 On Android"