LogUtil.java
2.85 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
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
package com.hjx.personalcenter.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class LogUtil
{
private static com.hjx.personalcenter.util.LogUtil _lg;
//single
public static com.hjx.personalcenter.util.LogUtil Instance(){
if(_lg == null){
_lg = new com.hjx.personalcenter.util.LogUtil();
}
return _lg;
}
//日志保存的数量 ,默认保存最近10天的日志
public int logSaveNum=10;
/**插入日志*/
public void WriteLog(String msg){
if(LOG_SWITCH){
System.out.println("插入日子的信息:" + msg);
File file = checkLogFileIsExist();
if(file == null)
return;
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(file, true);
fos.write((new Date().toLocaleString() + " " + msg).getBytes("gbk"));
fos.write("\r\n".getBytes("gbk"));
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally{
try
{
if(fos != null){
fos.close();
fos = null;
}
}
catch (IOException e)
{
e.printStackTrace();
}
fos = null;
file = null;
}
}
}
/**
* 打印异常堆栈信息
* @param e
* @return
*/
public void WriteStackTrace(Throwable e){
if(e != null){
//StringWriter sw = new StringWriter();
//PrintWriter pw = new PrintWriter(sw);
//e.printStackTrace(pw);
//return sw.toString();
WriteLog(e.getStackTrace().toString());
}
//return "";
}
private LogUtil()
{
CheckLogDele();
}
private void CheckLogDele()
{
//todo 扫描sd卡下面的日志文件,删除超过logSaveNum的日志
}
/**日志保存路径*/
private static final String LOG_SAVE_PATH = "/sdcard/Log/"; //sd卡上的日志文件目录
/**日志开关*/
private static final boolean LOG_SWITCH = true;
/**检查日志文件是否存在*/
private File checkLogFileIsExist(){
//if(!MemorySpaceManager.isSDExist()){ //sd 卡是否存在
// return null;
//}
File file = new File(LOG_SAVE_PATH);
if(!file.exists()){
file.mkdirs();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = sdf.format(new Date());
file = new File(LOG_SAVE_PATH + dateStr + ".txt");
if(!isLogExist(file)){
try
{
file.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
}
}
sdf = null;
return file;
}
/**
* 检查当天日志文件是否存在
* @param file
* @return
*/
private boolean isLogExist(File file){
File tempFile = new File(LOG_SAVE_PATH);
File[] files = tempFile.listFiles();
if(files!=null){
for(int i = 0; i < files.length; i++){
if(files[0].getName().trim().equalsIgnoreCase(file.getName())){
return true;
}
}
}
return false;
}
}