我是靠谱客的博主 欢喜柜子,这篇文章主要介绍android 日志文件LogUtils实例,现在分享给大家,希望可以做个参考。

背景

这是好久之前在网上找的一个常用类,已经忘记原文链接了,但是觉得很好用一直都在用,可以将日志写到file里面也可以定位你是在哪个类哪一行打印的日志,保存到文件的路径就是android/data/你的包名/files/目录下,然后我们就可以愉快的找问题了

复制代码
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
import android.text.TextUtils; import android.util.Log; import com.smartlink.suixing.App; import com.smartlink.suixing.BuildConfig; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Formatter; import java.util.Locale; public class LogUtils { public static String customTagPrefix = "log"; // 自定义Tag的前缀,可以是作者名 private static final boolean isSaveLog = true; // 是否把保存日志到SD卡中 private static String cacheDirPath; private LogUtils() { } // 容许打印日志的类型,默认是true,设置为false则不打印 public static boolean allowD = BuildConfig.DEBUG; public static boolean allowE = BuildConfig.DEBUG; public static boolean allowI = BuildConfig.DEBUG; public static boolean allowV = BuildConfig.DEBUG; public static boolean allowW = BuildConfig.DEBUG; public static boolean allowWtf = BuildConfig.DEBUG; // public static boolean allowD = true; // public static boolean allowE = true; // public static boolean allowI = true; // public static boolean allowV = true; // public static boolean allowW = true; // public static boolean allowWtf = true; private static String generateTag(StackTraceElement caller) { String tag = "%s.%s(Line:%d)"; // 占位符 String callerClazzName = caller.getClassName(); // 获取到类名 callerClazzName = callerClazzName.substring(callerClazzName.lastIndexOf(".") + 1); tag = String.format(tag, callerClazzName, caller.getMethodName(), caller.getLineNumber()); // 替换 tag = TextUtils.isEmpty(customTagPrefix) ? tag : customTagPrefix + ":" + tag; return tag; } /*** * 打印控制台显示不了那么长的日志问题 * * @param msg */ public static void logE(String msg) { // 信息太长,分段打印 if (!allowE) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); // 因为String的length是字符数量不是字节数量所以为了防止中文字符过多, // 把4*1024的MAX字节打印长度改为2001字符数 int max_str_length = 2001 - tag.length(); // 大于4000时 while (msg.length() > max_str_length) { // Log.e(tag, msg.substring(0, max_str_length)); LogUtils.e(msg.substring(0, max_str_length)); msg = msg.substring(max_str_length); } // 剩余部分 // Log.e(tag, msg); LogUtils.e(msg); } /** * 自定义的logger */ public static CustomLogger customLogger; public interface CustomLogger { void d(String tag, String content); void d(String tag, String content, Throwable tr); void e(String tag, String content); void e(String tag, String content, Throwable tr); void i(String tag, String content); void i(String tag, String content, Throwable tr); void v(String tag, String content); void v(String tag, String content, Throwable tr); void w(String tag, String content); void w(String tag, String content, Throwable tr); void w(String tag, Throwable tr); void wtf(String tag, String content); void wtf(String tag, String content, Throwable tr); void wtf(String tag, Throwable tr); } public static void d(String content) { if (!allowD) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.d(tag, content); } else { Log.d(tag, content); } } public static void d(String content, Throwable tr) { if (!allowD) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.d(tag, content, tr); } else { Log.d(tag, content, tr); } } public static void e(String content) { if (!allowE) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.e(tag, content); } else { Log.e(tag, content); } if (isSaveLog) { point(cacheDirPath, tag, content); } } public static void e(String content, Throwable tr) { if (!allowE) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.e(tag, content, tr); } else { Log.e(tag, content, tr); } if (isSaveLog) { point(cacheDirPath, tag, tr.getMessage()); } } public static void e(Throwable tr) { if (!allowE) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.e(tag, "", tr); } else { Log.e(tag, "", tr); } if (isSaveLog) { point(cacheDirPath, tag, tr.getMessage()); } } public static void i(String content) { if (!allowI) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.i(tag, content); } else { Log.i(tag, content); } } public static void i(String content, Throwable tr) { if (!allowI) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.i(tag, content, tr); } else { Log.i(tag, content, tr); } } public static void v(String content) { if (!allowV) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.v(tag, content); } else { Log.v(tag, content); } } public static void v(String content, Throwable tr) { if (!allowV) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.v(tag, content, tr); } else { Log.v(tag, content, tr); } } public static void w(String content) { if (!allowW) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.w(tag, content); } else { Log.w(tag, content); } } public static void w(String content, Throwable tr) { if (!allowW) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.w(tag, content, tr); } else { Log.w(tag, content, tr); } } public static void w(Throwable tr) { if (!allowW) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.w(tag, tr); } else { Log.w(tag, tr); } } public static void wtf(String content) { if (!allowWtf) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.wtf(tag, content); } else { Log.wtf(tag, content); } } public static void wtf(String content, Throwable tr) { if (!allowWtf) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.wtf(tag, content, tr); } else { Log.wtf(tag, content, tr); } } public static void wtf(Throwable tr) { if (!allowWtf) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.wtf(tag, tr); } else { Log.wtf(tag, tr); } } private static StackTraceElement getCallerStackTraceElement() { return Thread.currentThread().getStackTrace()[4]; } public static void point(String path, String tag, String msg) { if (isSDAva()) { path = cacheDirPath; Date date = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("", Locale.SIMPLIFIED_CHINESE); dateFormat.applyPattern("yyyy"); path = path + dateFormat.format(date) + "/"; dateFormat.applyPattern("MM"); path += dateFormat.format(date) + "/"; dateFormat.applyPattern("dd"); path += dateFormat.format(date) + ".log"; dateFormat.applyPattern("[yyyy-MM-dd HH:mm:ss]"); String time = dateFormat.format(date); File file = new File(path); if (!file.exists()) createDipPath(path); BufferedWriter out = null; try { out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true))); out.write(time + " " + tag + " " + msg + "rn"); } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } } } /** * 根据文件路径 递归创建文件 * * @param file */ public static void createDipPath(String file) { String parentFile = file.substring(0, file.lastIndexOf("/")); File file1 = new File(file); File parent = new File(parentFile); if (!file1.exists()) { parent.mkdirs(); try { file1.createNewFile(); LogUtils.e("日志文件的路径是" + file1.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } } } /** * A little trick to reuse a formatter in the same thread */ private static class ReusableFormatter { private Formatter formatter; private StringBuilder builder; public ReusableFormatter() { builder = new StringBuilder(); formatter = new Formatter(builder); } public String format(String msg, Object... args) { formatter.format(msg, args); String s = builder.toString(); builder.setLength(0); return s; } } private static final ThreadLocal<ReusableFormatter> thread_local_formatter = new ThreadLocal<ReusableFormatter>() { protected ReusableFormatter initialValue() { return new ReusableFormatter(); } }; public static String format(String msg, Object... args) { ReusableFormatter formatter = thread_local_formatter.get(); return formatter.format(msg, args); } public static boolean isSDAva() { if (cacheDirPath == null) cacheDirPath = App.getAppContext().getExternalFilesDir("log").getAbsolutePath(); if (!TextUtils.isEmpty(cacheDirPath)) { return true; } else { return false; } } }

补充知识:Android日志打印类LogUtils,能够定位到类名,方法名以及出现错误的行数并保存日志文件

在开发中,我们常常用打印log的方式来调试我们的应用。在Java中我们常常使用方法System.out.println()来在控制台打印日志,以便我们的调试。Android中有一个专门的类Log来实现在Android系统下日志的打印,更加方便我们定位程序出现问题的地方。  

但是Android官方提供的Log类在实际项目使用中,也不是非常方便。当程序出现错误时,我们最希望的就是这个Log类能帮我们定位到是哪个类的哪个方法,甚至于是那一行出现了错误。这样就能给我们的调试带来很大的便利。  

同时我们也应该想到为了应用程序的安全起见,在app正式上线之前,我们应该要把打印日志的功能关闭掉,以防别人通过Log来破解你的应用。生产模式的下打印Log,正式模式就把打印日志的功能关闭掉,要做到Log的灵活关闭与打开,也需要在原生的Log类上进行一些封装。  

还有一种时候,当我们的程序出现问题崩溃了,我们希望能够收集到出现异常的原因进行分析,所以可以把Log日志保存到一个文件中,放在SD卡程序创建的目录下。也可以在用户联网的情况下,在程序的后台把出异常的Log日志文件上传到服务端,方便程序员进行分析,解决bug。  

今天就给大家分享一个做项目中很实用的一个Log类LogUtils,这个类是从xUtils中提取出来,稍作修改的,有注释。  

示例:

我们在MainActivity中调用一些LogUtils中的方法,注意看行数。   1

接着看看控制台打印的日志是不是像MainActivity调用的那样,Log中有这个类的名字和oncreate方法名,已及当前行数;  2

看到上图中的Log日志是不是很方便定位程序中的问题了,出现异常也能快速的定位到。然后把下面的Log类型在程序的任何地方设置为false则不会打印日志,使用起来相当的方便。 

复制代码
1
2
3
4
5
6
7
// 容许打印日志的类型,默认是true,设置为false则不打印 public static boolean allowD = true; public static boolean allowE = true; public static boolean allowI = true; public static boolean allowV = true; public static boolean allowW = true; public static boolean allowWtf = true;

代码贴在下面:

复制代码
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
package com.finddreams.log; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Formatter; import java.util.Locale; import android.os.Environment; import android.text.TextUtils; import android.util.Log; /** * Log工具,类似android.util.Log。 tag自动产生,格式: * customTagPrefix:className.methodName(Line:lineNumber), * customTagPrefix为空时只输出:className.methodName(Line:lineNumber)。 */ public class LogUtils { public static String customTagPrefix = "finddreams"; // 自定义Tag的前缀,可以是作者名 private static final boolean isSaveLog = false; // 是否把保存日志到SD卡中 public static final String ROOT = Environment.getExternalStorageDirectory() .getPath() + "/finddreams/"; // SD卡中的根目录 private static final String PATH_LOG_INFO = ROOT + "info/"; private LogUtils() { } // 容许打印日志的类型,默认是true,设置为false则不打印 public static boolean allowD = true; public static boolean allowE = true; public static boolean allowI = true; public static boolean allowV = true; public static boolean allowW = true; public static boolean allowWtf = true; private static String generateTag(StackTraceElement caller) { String tag = "%s.%s(Line:%d)"; // 占位符 String callerClazzName = caller.getClassName(); // 获取到类名 callerClazzName = callerClazzName.substring(callerClazzName .lastIndexOf(".") + 1); tag = String.format(tag, callerClazzName, caller.getMethodName(), caller.getLineNumber()); // 替换 tag = TextUtils.isEmpty(customTagPrefix) ? tag : customTagPrefix + ":" + tag; return tag; } /** * 自定义的logger */ public static CustomLogger customLogger; public interface CustomLogger { void d(String tag, String content); void d(String tag, String content, Throwable tr); void e(String tag, String content); void e(String tag, String content, Throwable tr); void i(String tag, String content); void i(String tag, String content, Throwable tr); void v(String tag, String content); void v(String tag, String content, Throwable tr); void w(String tag, String content); void w(String tag, String content, Throwable tr); void w(String tag, Throwable tr); void wtf(String tag, String content); void wtf(String tag, String content, Throwable tr); void wtf(String tag, Throwable tr); } public static void d(String content) { if (!allowD) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.d(tag, content); } else { Log.d(tag, content); } } public static void d(String content, Throwable tr) { if (!allowD) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.d(tag, content, tr); } else { Log.d(tag, content, tr); } } public static void e(String content) { if (!allowE) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.e(tag, content); } else { Log.e(tag, content); } if (isSaveLog) { point(PATH_LOG_INFO, tag, content); } } public static void e(String content, Throwable tr) { if (!allowE) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.e(tag, content, tr); } else { Log.e(tag, content, tr); } if (isSaveLog) { point(PATH_LOG_INFO, tag, tr.getMessage()); } } public static void i(String content) { if (!allowI) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.i(tag, content); } else { Log.i(tag, content); } } public static void i(String content, Throwable tr) { if (!allowI) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.i(tag, content, tr); } else { Log.i(tag, content, tr); } } public static void v(String content) { if (!allowV) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.v(tag, content); } else { Log.v(tag, content); } } public static void v(String content, Throwable tr) { if (!allowV) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.v(tag, content, tr); } else { Log.v(tag, content, tr); } } public static void w(String content) { if (!allowW) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.w(tag, content); } else { Log.w(tag, content); } } public static void w(String content, Throwable tr) { if (!allowW) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.w(tag, content, tr); } else { Log.w(tag, content, tr); } } public static void w(Throwable tr) { if (!allowW) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.w(tag, tr); } else { Log.w(tag, tr); } } public static void wtf(String content) { if (!allowWtf) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.wtf(tag, content); } else { Log.wtf(tag, content); } } public static void wtf(String content, Throwable tr) { if (!allowWtf) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.wtf(tag, content, tr); } else { Log.wtf(tag, content, tr); } } public static void wtf(Throwable tr) { if (!allowWtf) return; StackTraceElement caller = getCallerStackTraceElement(); String tag = generateTag(caller); if (customLogger != null) { customLogger.wtf(tag, tr); } else { Log.wtf(tag, tr); } } private static StackTraceElement getCallerStackTraceElement() { return Thread.currentThread().getStackTrace()[4]; } public static void point(String path, String tag, String msg) { if (isSDAva()) { Date date = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("", Locale.SIMPLIFIED_CHINESE); dateFormat.applyPattern("yyyy"); path = path + dateFormat.format(date) + "/"; dateFormat.applyPattern("MM"); path += dateFormat.format(date) + "/"; dateFormat.applyPattern("dd"); path += dateFormat.format(date) + ".log"; dateFormat.applyPattern("[yyyy-MM-dd HH:mm:ss]"); String time = dateFormat.format(date); File file = new File(path); if (!file.exists()) createDipPath(path); BufferedWriter out = null; try { out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(file, true))); out.write(time + " " + tag + " " + msg + "rn"); } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } } } /** * 根据文件路径 递归创建文件 * * @param file */ public static void createDipPath(String file) { String parentFile = file.substring(0, file.lastIndexOf("/")); File file1 = new File(file); File parent = new File(parentFile); if (!file1.exists()) { parent.mkdirs(); try { file1.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } } /** * A little trick to reuse a formatter in the same thread */ private static class ReusableFormatter { private Formatter formatter; private StringBuilder builder; public ReusableFormatter() { builder = new StringBuilder(); formatter = new Formatter(builder); } public String format(String msg, Object... args) { formatter.format(msg, args); String s = builder.toString(); builder.setLength(0); return s; } } private static final ThreadLocal<ReusableFormatter> thread_local_formatter = new ThreadLocal<ReusableFormatter>() { protected ReusableFormatter initialValue() { return new ReusableFormatter(); } }; public static String format(String msg, Object... args) { ReusableFormatter formatter = thread_local_formatter.get(); return formatter.format(msg, args); } public static boolean isSDAva() { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED) || Environment.getExternalStorageDirectory().exists()) { return true; } else { return false; } } }

以上这篇android 日志文件LogUtils实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持靠谱客。

最后

以上就是欢喜柜子最近收集整理的关于android 日志文件LogUtils实例的全部内容,更多相关android内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(119)

评论列表共有 0 条评论

立即
投稿
返回
顶部