创建 FileLoggingTree.java
parent
b4ce52bbdc
commit
f161762d92
|
|
@ -0,0 +1,59 @@
|
|||
package com.nbee.echolink;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.Log;
|
||||
import timber.log.Timber;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
|
||||
public class FileLoggingTree extends Timber.DebugTree {
|
||||
private final File logFile;
|
||||
|
||||
public FileLoggingTree(Context context) {
|
||||
File logDirectory = new File(context.getFilesDir(), "logs");
|
||||
if (!logDirectory.exists()) {
|
||||
logDirectory.mkdirs();
|
||||
}
|
||||
this.logFile = new File(logDirectory, "echoLink.log");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void log(int priority, String tag, String message, Throwable t) {
|
||||
super.log(priority, tag, message, t);
|
||||
|
||||
try (FileWriter fileWriter = new FileWriter(logFile, true)) {
|
||||
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
|
||||
String timestamp = dateFormat.format(new Date());
|
||||
String logMessage = timestamp + " [" + priorityToString(priority) + "] " + tag + ": " + message + "\n";
|
||||
fileWriter.append(logMessage);
|
||||
|
||||
if (t != null) {
|
||||
fileWriter.append(Log.getStackTraceString(t)).append("\n");
|
||||
}
|
||||
} catch (IOException e) {
|
||||
Log.e("FileLoggingTree", "Error writing log to file", e);
|
||||
}
|
||||
}
|
||||
|
||||
private String priorityToString(int priority) {
|
||||
switch (priority) {
|
||||
case Log.ERROR:
|
||||
return "ERROR";
|
||||
case Log.WARN:
|
||||
return "WARN";
|
||||
case Log.INFO:
|
||||
return "INFO";
|
||||
case Log.DEBUG:
|
||||
return "DEBUG";
|
||||
case Log.VERBOSE:
|
||||
return "VERBOSE";
|
||||
default:
|
||||
return "UNKNOWN";
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue