0%

安卓logutils工具类

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111


import android.content.Context;
import android.util.Log;

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 LogUtils {
private static final String DEFAULT_TAG = "AppLog";
private static boolean isDebug = true;
private static boolean writeToFile = true;

private static final String LOG_FILE_PREFIX = "log_"; // 文件名前缀
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
private static final SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss.SSS", Locale.CHINA);

// 记录应用上下文,初始化时调用
private static Context sContext;

public static void init(Context context) {
sContext = context.getApplicationContext();
}

public static void setDebug(boolean debug) {
isDebug = debug;
}

public static void setWriteToFile(boolean write) {
writeToFile = write;
}

public static void d(String msg) {
d(DEFAULT_TAG, msg);
}

public static void d(String tag, String msg) {
if (isDebug && msg != null) {
Log.d(tag, msg);
writeLogToFile("D", tag, msg);
}
}

public static void i(String msg) {
i(DEFAULT_TAG, msg);
}

public static void i(String tag, String msg) {
if (isDebug && msg != null) {
Log.i(tag, msg);
writeLogToFile("I", tag, msg);
}
}

public static void w(String msg) {
w(DEFAULT_TAG, msg);
}

public static void w(String tag, String msg) {
if (isDebug && msg != null) {
Log.w(tag, msg);
writeLogToFile("W", tag, msg);
}
}

public static void e(String msg) {
e(DEFAULT_TAG, msg);
}

public static void e(String tag, String msg) {
if (isDebug && msg != null) {
Log.e(tag, msg);
writeLogToFile("E", tag, msg);
}
}

public static void e(String tag, String msg, Throwable tr) {
if (isDebug && msg != null) {
Log.e(tag, msg, tr);
writeLogToFile("E", tag, msg + "\n" + Log.getStackTraceString(tr));
}
}

private static void writeLogToFile(String level, String tag, String message) {
if (!writeToFile || sContext == null) return;

try {
String today = dateFormat.format(new Date());
String time = timeFormat.format(new Date());

// 使用应用私有外部存储目录: /Android/data/你的包名/files/AppLogs/
File logDir = new File(sContext.getExternalFilesDir(null), "AppLogs");
if (!logDir.exists()) {
logDir.mkdirs();
}

File logFile = new File(logDir, LOG_FILE_PREFIX + today + ".txt");
FileWriter writer = new FileWriter(logFile, true);
writer.write(String.format("[%s][%s][%s]: %s\n", time, level, tag, message));
writer.flush();
writer.close();
} catch (IOException e) {
Log.e("LogUtils", "writeLogToFile failed: " + e.getMessage());
}
}
}