Skip to content
Advertisement

LOG4J in Android

I have a Java Project with a lot of files, which is using LOG4J. Now I am trying to Port it to the Android platform. Is it possible to reuse the code as it is, with LOG4J function calls?

Current understanding:

  1. Property configuration won’t work (beans dependency)
  2. I tried with LOG4J for Android and SL4J Lib. No success.

Working. But no use

org.apache.log4j.Logger root = org.apache.log4j.Logger.getRootLogger();
final SocketAppender appender = new SocketAppender("192.168.123.123", 3333);
root.addAppender(appender);

// SLF4J - Not working
org.slf4j.Logger logger;
logger = LoggerFactory.getLogger(MyClass.class); 

// LOG4J for Android - Not working
ConfigureLog4J.configure();
logger = Logger.getLogger( MyClass.class );

Am I missing something? Pointer to any working examples?

Advertisement

Answer

Solved by using the android-logging-log4j.jar.

Here is sample code:

public class ALogger {
    public static org.apache.log4j.Logger getLogger(Class clazz) {
        final LogConfigurator logConfigurator = new LogConfigurator();
        logConfigurator.setFileName(Environment.getExternalStorageDirectory().toString() + File.separator + "log/file.log");
        logConfigurator.setRootLevel(Level.ALL);
        logConfigurator.setLevel("org.apache", Level.ALL);
        logConfigurator.setUseFileAppender(true);
        logConfigurator.setFilePattern("%d %-5p [%c{2}]-[%L] %m%n");
        logConfigurator.setMaxFileSize(1024 * 1024 * 5);
        logConfigurator.setImmediateFlush(true);
        logConfigurator.configure();
        Logger log = Logger.getLogger(clazz);
        return log;
    }
}

In your code, replace the below lines:

PropertyConfigurator.configure(MY_PROP_FILE);
logger = Logger.getLogger( MyClaZZ.class );

With:

logger = ALogger.getLogger(MyClazz.class);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement