log4j support in Android

I am attempting to shoehorn an existing SDK onto an android device and one of the dependencies of said SDK is Apache log4j. I am able to load my test program onto the android emulator but when the log4j object "PropertySetter" is called the program fails with a verification exception. Is there a way to ameliorate this issue?


Solution 1:

Actually using slf4j turned out a remarkably painless process for me, and it seems the common case, at least for libraries that use straightforward log4j features. You don't really need to swap slf4j in for log4j, only add two slf4j libraries to your project from http://www.slf4j.org/download.html:

-- the slf4j library for Android (currently slf4j-android-1.6.1-RC1.jar)
-- the log4j over slf4j (http://www.slf4j.org/legacy.html#log4j-over-slf4j) bridge.

The latter defines the core log4j classes used by typical implementations and bind them to the slf4j Android implementation. Once the libraries are added the code works.

Solution 2:

I successfully got log4j working on android with a Socket Appender and Log4j Chainsaw. All code is located in this repository. Slf4j set up and working too. Be aware you have to configure it programmatically. You cannot use .properties or .xml files the parser wont work on android. Enjoy.

https://sourceforge.net/projects/log4j-android/

Solution 3:

There is a new project, which enables log4j on android. Also using log4j over slf4j is possible. It also provides an appender for LogCat. See Logging in Android using Log4J.

The following example shows how to configure and use log4j in Android.

Configure the log4j system in Android

import org.apache.log4j.Level;
import android.os.Environment;
import de.mindpipe.android.logging.log4j.LogConfigurator;
/**
 * Simply place a class like this in your Android applications classpath.
 */
public class ConfigureLog4J {
    static {
        final LogConfigurator logConfigurator = new LogConfigurator();

        logConfigurator.setFileName(Environment.getExternalStorageDirectory() + "myapp.log");
        logConfigurator.setRootLevel(Level.DEBUG);
        // Set log level of a specific logger
        logConfigurator.setLevel("org.apache", Level.ERROR);
        logConfigurator.configure();
    }
}

Logging in Android using log4j using slf4j API

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ExampleLog4JOverSLF4J {
    private final Logger log = LoggerFactory.getLogger(ExampleLog4JOverSLF4J.class);

    public void myMethod() {
        log.info("This message should be seen in log file and logcat");
    }
}

Logging in Android using log4j API

import org.apache.log4j.Logger;

public class ExampleLog4J {
    private final Logger log = Logger.getLogger(LogConfiguratorTest.class);

    public void myMethod() {
        log.info("This message should be seen in log file and logcat");
    }
}