在安卓中,默认情况下,Log类会将日志写入控制台(logcat)。是否有一种简单的方法来将日志写入文件中?
在安卓中,默认情况下,Log类会将日志写入控制台(logcat)。是否有一种简单的方法来将日志写入文件中?
一个简单的Log
类(仅用于开发/测试目的),类似于android.util.Log
,但日志记录到SD卡。 唯一对现有代码的修改将是更改import android.util.Log
为import com.example.Log
。 还需要添加权限:<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
package com.example.logger;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.os.Environment;
public class Log {
private static final String NEW_LINE = System.getProperty("line.separator") ;
public static boolean mLogcatAppender = true;
final static File mLogFile;
static {
mLogFile = new File( Environment.getExternalStorageDirectory(), "logs.log" );
if ( !mLogFile.exists() ) {
try {
mLogFile.createNewFile();
}
catch (final IOException e) {
e.printStackTrace();
}
}
logDeviceInfo();
}
public static void i( String TAG, String message ){
appendLog( TAG + " : " + message );
if ( mLogcatAppender ) {
android.util.Log.i( TAG, message );
}
}
public static void d( String TAG, String message ){
appendLog( TAG + " : " + message );
if ( mLogcatAppender ) {
android.util.Log.d( TAG, message );
}
}
public static void e( String TAG, String message ){
appendLog( TAG + " : " + message );
if ( mLogcatAppender ) {
android.util.Log.e( TAG, message );
}
}
public static void v(String TAG, String message ){
appendLog(TAG + " : " + message);
if ( mLogcatAppender ) {
android.util.Log.v( TAG, message );
}
}
public static void w( String TAG, String message ) {
appendLog( TAG + " : " + message );
if ( mLogcatAppender ) {
android.util.Log.w( TAG, message );
}
}
private static synchronized void appendLog( String text ) {
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
try {
final FileWriter fileOut = new FileWriter( mLogFile, true );
fileOut.append( sdf.format(new Date()) + " : " + text + NEW_LINE );
fileOut.close();
}
catch ( final IOException e ) {
e.printStackTrace();
}
}
private static void logDeviceInfo() {
appendLog("Model : " + android.os.Build.MODEL);
appendLog("Brand : " + android.os.Build.BRAND);
appendLog("Product : " + android.os.Build.PRODUCT);
appendLog("Device : " + android.os.Build.DEVICE);
appendLog("Codename : " + android.os.Build.VERSION.CODENAME);
appendLog("Release : " + android.os.Build.VERSION.RELEASE);
}
}
adb shell logcat > log.txt
。stdout
和stderr
重定向到文件,我记得这样做可以,但我没有带手机来测试。使用FileInputStream将所有错误消息重定向到文件