When i was playing with this library, i have created a simple application. I hope it will be helpful for you.
First, add log4j-#.#.#.jar and android-logging-log4j-#.#.#.jar files to project add a reference.
After that, i have created a helper class for configuration and logger object.
public class Log4jHelper {
private final static LogConfigurator _logConfigurator = new LogConfigurator();
public static void Configure(String fileName, String filePattern,
int maxBackupSize, long maxFileSize) {
// set the name of the log file
_logConfigurator.setFileName(fileName);
// set output format of the log line
_logConfigurator.setFilePattern(filePattern);
// Maximum number of backed up log files
_logConfigurator.setMaxBackupSize(maxBackupSize);
// Maximum size of log file until rolling
_logConfigurator.setMaxFileSize(maxFileSize);
// configure
_logConfigurator.configure();
}
public static Logger getLogger(String name) {
Logger logger = Logger.getLogger(name);
return logger;
}
}
And, i have written a few line of codes in Application onCreate event for log4j configuration
public class Log4jApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// configure log4j
configureLog4j();
}
private void configureLog4j() {
String fileName = Environment.getExternalStorageDirectory() + "/" + "log4j.log";
String filePattern = "%d - [%c] - %p : %m%n";
int maxBackupSize = 10;
long maxFileSize = 1024 * 1024;
Log4jHelper.Configure(fileName, filePattern, maxBackupSize, maxFileSize);
}
}
Of course don't forget the
WRITE_EXTERNAL_STORAGE permission in AndroidManifest.xml file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
We are ready :) Let's write some logs :
Logger mLog = Logger.getLogger(Log4jActivity.class);
// write some logs
mLog.error("This is an error");
mLog.info("This is an info");
mLog.warn("This is a warn");
// write some exception
try {
String dummyString = null;
if (dummyString.equals("something")) {
int dummyInt = 1;
}
} catch (Exception ex) {
mLog.error(ex.toString(), ex);
}
You can find source code and sample usage on
6 comments:
good one...
Is it possible o rollover logs based on date?
Is is possible to configure a RollingFIleAppender with this ?
Getting Error
public static Logger getLogger(String name) {
Logger logger = Logger.getLogger(name);
return logger;
}
you have given String parameter but while calling in Activity you are giving ur activity class name
Logger mLog = Logger.getLogger(Log4jActivity.class);
there is incomparibility..
I'm glad to hear about the android-logging-log4j library as I will definitely look into using that for my Android projects.
Post a Comment