Friday, June 10, 2011

[Android]Use MicroLog4j in Android

之前寫的專案一直在無法預期的時間發生FC(Forced close),為了抓到這隻bug,必須在軟體中記錄log。雖然Android中已經有Logcat的機制,但是我總不可能手機一直連接在電腦上,在程式被FC之前一直盯著console看吧?所以最好的辦法就是寫Log,寫Log是我自己要看的,正式的版本不會加入此功能。


上網爬了一些文章,大部分的記錄Log教學都是使用logcat,後來找到Java web based-application上常常使用的log4j之簡化版本:microlog4android,使用的方法節錄於原作者的Blog: Microlog, Microlog4Android, SLF4J and Other Stuff

1. Add the following static variable in your main Activity:

private static final Logger logger = LoggerFactory.getLogger();

2. Add the following to your onCreate() method:

PropertyConfigurator.getConfigurator(this).configure();

3. Create a file named microlog.properties and store it in /assets

4. Edit the microlog.properties file as follows:

microlog.level=DEBUG
microlog.appender=LogCatAppender;FileAppender
microlog.formatter=PatternFormatter
microlog.formatter.PatternFormatter.pattern=%c [%P] %m %T

5. Add logging statements like this:

logger.debug("M4A");

For each class you create a logger object as specified in 1)

6.You may be add the following permission:

android.permission.WRITE_EXTERNAL_STORAGE"


complier程式之後,如果有Log產生,會看到SD卡裡面有一個名為microlog.txt的檔案,就是它囉!

0 comments:

Post a Comment