這是本人見過寫博文最負責的一個人:
http://www.crifan.com/android_try_use_android_logging_log4j_to_output_log_to_sd_card_file/
為什么說他負責呢??
因為作者寫出了從確定需求到找到解決方案的整個過程,不僅會讓讀者少走彎路,還把解決方案全盤托出,簡直是太贊啦!
當然也有些廢話,把它的精華吸收過來,廢話不說,上干貨:
在android中,實現輸出log內容到sd卡中的文件里面,做法是:
1.下載android的log4j的庫
去:http://code.google.com/p/android-logging-log4j/
下載對應的android-logging-log4j-1.0.3.jar,加到項目中。
2.再去下載所依賴的apache的log4j庫
去:http://logging.apache.org/log4j/1.2/download.html
下載1.2系列版本的:log4j-1.2.17.zip
解壓得到log4j-1.2.17.jar加到項目中。
3.寫測試代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
import
de.mindpipe.android.logging.log4j.LogConfigurator;
import
java.io.File;
import
android.os.Environment;
import
org.apache.log4j.Level;
import
org.apache.log4j.Logger;
public
class
BaseActivity
extends
Activity {
private
Logger gLogger;
public
void
configLog()
{
final
LogConfigurator logConfigurator =
new
LogConfigurator();
logConfigurator.setFileName(Environment.getExternalStorageDirectory() + File.separator +
"crifanli_log4j.log"
);
// Set the root log level
logConfigurator.setRootLevel(Level.DEBUG);
// Set log level of a specific logger
logConfigurator.setLevel(
"org.apache"
, Level.ERROR);
logConfigurator.configure();
//gLogger = Logger.getLogger(this.getClass());
gLogger = Logger.getLogger(
"CrifanLiLog4jTest"
);
}
@Override
protected
void
onCreate(Bundle savedInstanceState) {
configLog();
gLogger.debug(
"test android log to file in sd card using log4j"
);
|
即可實現:
(1)可以在/mnt/sdcard中生成對應的crifanli_log4j.log文件
(2)log輸出的內容中,是DEBUG,且對應的是自己的字符串標識符CrifanLiLog4jTest