[英]android writing log statements to sdcard
我正在嘗試將日志語句寫入SD卡。 我決定這樣做的方法是通過Application Object在SD卡上創建一個文件。 這樣我就可以從應用程序的任何地方調用靜態方法logToSdcard()。
創建了包含文件夾“/ RR3log /”,但我記錄的每個語句都在其自己的文件中,名為“rr3LogFile.txt”。 所以我有多個rr3LogFile文件,每個文件包含一個staement。
如何將所有語句寫入一個rr3LogFile文件? 在此先感謝馬特。
public class NfcScannerApplication extends Application{
@Override
public void onCreate() {
super.onCreate();
File storageDir = new File(Environment
.getExternalStorageDirectory(), "/RR3log/");
storageDir.mkdir();
try {
if(outfile == null){
outfile=File.createTempFile("rr3LogFile", ".txt",storageDir);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void logToSdcard(String tag, String statement){
Log.e(TAG, "inside logtosdcard$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
String state = android.os.Environment.getExternalStorageState();
if(!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
try {
throw new IOException("SD Card is not mounted. It is " + state + ".");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
DateTime now = new DateTime();
DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y H:mm");
String dateStr = fmt.print(now);
try{
FileOutputStream fOut = new FileOutputStream(outfile);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.append(dateStr + " " + tag + " ");
myOutWriter.append(statement);
myOutWriter.append("\n");
myOutWriter.flush();
myOutWriter.close();
fOut.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
。
然后在應用程序中的任何位置的Activity中。
@Override
protected void onResume() {
super.onResume();
Log.e(TAG, "inside entryactivity onResume");
NfcScannerApplication.logToSdcard(TAG, "inside entryactivity onResume" );
在logToSdcard
方法中,使用附加參數創建FileOutputStream:
FileOutputStream fOut = new FileOutputStream(outfile, true);
true
參數表示內容將附加到文件中。 另請參見FileOutputStream
試試看:
public static void printLog(Context context){
String filename = context.getExternalFilesDir(null).getPath() + File.separator + "my_app.log";
String command = "logcat -f "+ filename + " -v time -d *:V";
Log.d(TAG, "command: " + command);
try{
Runtime.getRuntime().exec(command);
}
catch(IOException e){
e.printStackTrace();
}
}
日志將連續保存,直到退出應用程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.