監聽Log 並寫入文件

public class NoteLog {

//Log信息 保存路徑
private static final String FILE_PATH = "/sdcard/log/";
private static final String LOG_PATH = FILE_PATH + "log.txt";
private static final int LOG_FILE_MAX_SIZE = 50;//50 KB
static Thread readLogthread;
static BufferedReader reader = null;
static Boolean isStop = false;
static FileOutputStream out = null;

public static void startNoteLog() {
startNoteLogThread();
}

public static void stopNoteLog() {
isStop = true;
closeLogReader();
if (readLogthread != null) {
readLogthread.interrupt();
}
}

private static void startNoteLogThread() {
/** 開啓線程用於監聽log輸出的信息 **/
readLogthread = new Thread() {
@Override
public void run() {
try {
readLogcatInfo();
} catch (IOException e) {
e.printStackTrace();
} finally {
closeLogReader();
}
}
};
readLogthread.start();
}

private static void readLogcatInfo() throws IOException {
Process mLogcatProc = null;
String line = "";
// 清除LOG
Runtime.getRuntime().exec("logcat -c");
ArrayList<String> commandLine = new ArrayList<String>();
commandLine.add("logcat");
commandLine.add("-v");
commandLine.add("time");
commandLine.add("-s");
commandLine.add("AndroidRuntime:e"); // *表示所有TAG(*:e)
mLogcatProc = Runtime.getRuntime().exec(
commandLine.toArray(new String[commandLine.size()]));
reader = new BufferedReader(new InputStreamReader(mLogcatProc
.getInputStream()));
while (!isStop && (line = reader.readLine()) != null) {
write(line);
}
}


private static void write(String data) {
try {
File file = new File(FILE_PATH);
if (!file.exists()) {
file.mkdir();
}
File logFile = new File(LOG_PATH);
if (logFile.exists()) {
if (logFile.length() > 1024 * LOG_FILE_MAX_SIZE) {
logFile.delete();
}
}
out = new FileOutputStream(LOG_PATH, true);
if (data != null && !data.contains("beginning")) {
out.write(data.getBytes());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
out = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

private static void closeLogReader() {
try {
if (out != null) {
out.close();
out = null;
}
if (reader != null) {
reader.close();
reader = null;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

在manifest.xml中增加權限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-permission android:name="android.permission.READ_LOGS" />

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章