WMSLog.java
2.87 KB
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
package com.huaheng.common;
import android.util.Log;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
public class WMSLog {
private final static String TAG = "WMSLog";
private static boolean DEBUG = true;
private static ScheduledExecutorService sExecutor;
private static String path = Constant.LOG_PATH;
public static void i(String msg) {
Log.i(TAG, msg);
input2File(msg, path);
}
public static void d(String msg) {
if(DEBUG) {
Log.i(TAG, msg);
input2File(msg, path);
}
}
/**
* 将内容直接写过文件中,自己设置路径
* 这个是一边打印日志,一边将日志写入到file
* 不建议直接new一个子线程做写入逻辑,建议开启线程池,避免到处开启线程损耗性能
* @param input 写入内容
* @param dirPath 文件夹
* @return
*/
private static boolean input2File(String input, String dirPath) {
File dir = new File(dirPath);
if (!dir.exists()) {
dir.mkdirs();
}
input = WMSUtils.getLogHeaderName() + " " + input + " \n";
String fileName = WMSUtils.getLogTimeName() + ".txt";
final String filePath = dirPath + fileName;
if (sExecutor == null) {
sExecutor = Executors.newScheduledThreadPool(5);
}
final String finalInput = input;
Future<Boolean> submit = sExecutor.submit(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
BufferedWriter bw = null;
try {
// 构造给定文件名的FileWriter对象,并使用布尔值指示是否追加写入的数据。
FileWriter fileWriter = new FileWriter(filePath, true);
bw = new BufferedWriter(fileWriter);
bw.write(finalInput);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
if (bw != null) {
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
try {
return submit.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return false;
}
}