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?

1

3 Answers

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);
1

My answer, that presents a more future-proof and lateral-thinking approach ;-).

I was using android-logging-log4j myself for some time, but it was causing massive warnings (which actually looked like errors) while dexing.

The log4j jar also had a lot of unnecessary stuff in it, like the Chainsaw logging UI (written in Swing, thus useless on Android).

I've switched to logback via . So far I'm happy. No more massive spam while building.

Plus, looks like log4j 1.x is not developed anymore, look at - last commit many years ago.

And logback seems to be the successor.

0

Take a look at android-log4j2. The project provides runtime dependency jar which does not require you to change any of your log4j dependent code and adapts all the logs to Android logging. There is no API to learn.

It's a drop in replacement for log4j-core, so only make sure to swap it out with
android-log4j2 in your android project.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like