Admin
2021-06-11 979f3ede5b10d3f873c1f1bd2aa400e2219742a0
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
package com.anyun.basecommonlib;
 
 
 
 
 
 
/**
 * anyunProject(20190906)
 * Created by lzw on 2019/9/6. 17:23:17
 * 邮箱:632393724@qq.com
 * All Rights Saved! Chongqing AnYun Tech co. LTD
 */
 
 
import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
 
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class MyLog {
 
     private static final String TAG = "AYJiaKao";
 
 
    // 日志文件在sdcard中的路径
    private static String MYLOG_PATH_SDCARD_DIR = "/sdcard/JiaKaolog";
 
 
    private static Boolean MYLOG_SWITCH = true; // 日志文件总开关
 
    private static Boolean MYLOG_WRITE_TO_FILE = true;// 日志写入文件开关
    private static File file;
 
    // 输入日志类型,w代表只输出告警信息等,v代表输出所有信息
    private static char MYLOG_TYPE = 'v';
 
    // 日志文件在sdcard中的路径
 
    private static int SDCARD_LOG_FILE_SAVE_DAYS = 7;// sd卡中日志文件的最多保存天数
 
    private static String MYLOGFILEName = "Log.txt";// 本类输出的日志文件名称
 
    private static SimpleDateFormat myLogSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 日志的输出格式
 
    private static SimpleDateFormat logfile = new SimpleDateFormat("yyyy-MM-dd");// 日志文件格式
 
    public Context context;
 
 
    public static void w(String tag, Object msg) { // 警告信息
 
        log(tag, msg.toString(), 'w');
 
    }
 
 
    public static void e(String tag, Object msg) { // 错误信息
 
        log(tag, msg.toString(), 'e');
 
    }
 
 
    public static void d(String tag, Object msg) {// 调试信息
 
        log(tag, msg.toString(), 'd');
 
    }
 
 
    public static void i(String tag, Object msg) {//
 
        log(tag, msg.toString(), 'i');
 
    }
 
    public static void i(Object msg) {//
 
        log(TAG, msg.toString(), 'i');
 
    }
 
 
    public static void v(String tag, Object msg) {
 
        log(tag, msg.toString(), 'v');
 
    }
 
 
    public static void w(String tag, String text) {
 
        log(tag, text, 'w');
 
    }
 
 
    public static void e(String tag, String text) {
 
        log(tag, text, 'e');
 
    }
 
 
    public static void d(String tag, String text) {
 
        log(tag, text, 'd');
 
    }
 
 
    public static void i(String tag, String text) {
 
        log(tag, text, 'i');
 
    }
 
    public static void i(String text) {
 
        log(TAG, text, 'i');
 
    }
 
 
    public static void v(String tag, String text) {
 
        log(tag, text, 'v');
 
    }
 
 
    /**
     * 根据tag, msg和等级,输出日志
     *
     * @param tag
     * @param msg
     * @param level
     */
 
    private static void log(final String tag, final String msg, final char level) {
 
        if (MYLOG_SWITCH) {//日志文件总开关
 
            if ('e' == level && ('e' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) { // 输出错误信息
 
                Log.e(tag, msg);
 
            } else if ('w' == level && ('w' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) {
 
                Log.w(tag, msg);
 
            } else if ('d' == level && ('d' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) {
 
                Log.d(tag, msg);
 
            } else if ('i' == level && ('d' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) {
 
                Log.i(tag, msg);
 
            } else {
 
                Log.v(tag, msg);
 
            }
 
            if (MYLOG_WRITE_TO_FILE)//日志写入文件开关
 
//                Executors.newSingleThreadExecutor().execute(new Runnable() {
//                    @Override
//                    public void run() {
                        writeLogtoFile( tag, msg);
//                    }
//                });
 
        }
 
    }
 
    public static void createIfNotExist() {
 
 
        String needWriteFiel = logfile.format(System.currentTimeMillis());
 
 
        Log.i(TAG, "createIfNotExist: " + needWriteFiel);
 
 
        File dirsFile = new File(MYLOG_PATH_SDCARD_DIR);
 
        if (!dirsFile.exists()) {
 
            dirsFile.mkdirs();
 
        }
 
        //Log.i("创建文件","创建文件");
 
        file = new File(dirsFile.toString(), needWriteFiel + MYLOGFILEName);// MYLOG_PATH_SDCARD_DIR
 
        if (!file.exists()) {
 
            try {
 
                //在指定的文件夹中创建文件
 
                file.createNewFile();
 
            } catch (Exception e) {
 
            }
 
        }
    }
 
    /**
     * 打开日志文件并写入日志
     *
     * @param mylogtype
     * @param tag
     * @param text
     */
 
    private static void writeLogtoFile(String mylogtype, final String tag, final String text) {// 新建或打开日志文件
 
        String needWriteMessage = myLogSdf.format(System.currentTimeMillis()) + " " + tag + "  " + text;
 
        try {
/**后面这个参数代表是不是要接上文件中原来的数据,不进行覆盖**/
            if (file != null){
                if (!file.getName().contains(logfile.format(System.currentTimeMillis()))){
                    Log.i(TAG, "writeLogtoFile: 当前file不是当前日期的,置为null");
                    file = null;
                }
            }
            if (file == null) {
                Log.i(TAG, "writeLogtoFile: file==null");
                createIfNotExist();
            }
            FileWriter filerWriter = new FileWriter(file, true);
 
            BufferedWriter bufWriter = new BufferedWriter(filerWriter);
 
            bufWriter.write(needWriteMessage);
 
            bufWriter.newLine();
 
            bufWriter.close();
 
            filerWriter.close();
 
        } catch (IOException e) {
 
            e.printStackTrace();
 
        }
    }
    /**
     * 打开日志文件并写入日志
     *
     * @param tag
     * @param text
     */
    static int count=0;
    private static synchronized void writeLogtoFile( final String tag, final String text) {// 新建或打开日志文件
 
        String needWriteMessage = myLogSdf.format(System.currentTimeMillis()) + " " + tag + "  " + text;
 
        try {
/**后面这个参数代表是不是要接上文件中原来的数据,不进行覆盖**/
 
 
            //先检查存在的file,如果存在没有写满(小于1MB的)的 则返回File。如果返回null,则要新建
 
            file =  checkExistFilesAndCreateFile();
 
 
            FileWriter filerWriter = new FileWriter(file, true);
 
            BufferedWriter bufWriter = new BufferedWriter(filerWriter);
 
            bufWriter.write(needWriteMessage);
 
            bufWriter.newLine();
 
            bufWriter.close();
 
            filerWriter.close();
 
        } catch (IOException e) {
 
            e.printStackTrace();
 
        }
    }
 
    private static final String PREFREIX = "jiaKao_appLog";
    private static synchronized File checkExistFilesAndCreateFile() {
        String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/JiaKaolog";
        File dirsFile  = new File(dirPath);
        if (!dirsFile.exists()){
            Log.i(TAG,"文件目录不存在,创建/nvlog...");
            dirsFile.mkdirs();
        }
        File tempFile = null;
        for (int j = 0; j < 5; j++) {
            tempFile = new File(dirPath,PREFREIX+j+".txt");
 
            if (tempFile.length()>20*1024*1024) {
                if (j==4){
                    Log.i(TAG,"删除第一个文件");
                    File file = new File(dirPath,PREFREIX+"0.txt");
                    file.delete();
                    Log.i(TAG,"重命名其他文件");
                    rename();
                    return new File(dirPath,PREFREIX+"4.txt");
                }
 
 
                continue;
 
 
 
            }else{
//                Log.i(TAG,String.format("返回文件%s",tempFile.getName()));
                break;
            }
 
        }
//        Log.i(TAG,String.format("返回文件null"));
        return tempFile;
    }
 
    private static void rename() {
        String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/JiaKaolog";
        for (int i = 1; i < 5; i++) {
            File file = new File(dirPath,PREFREIX+i+".txt");
            File fileSrc = new File(dirPath,PREFREIX+(i-1)+".txt");
            file.renameTo(fileSrc);
        }
 
    }
 
 
    /**
     * 删除制定的日志文件
     */
 
    public static void delFile() {// 删除日志文件
 
        String needDelFiel = logfile.format(getDateBefore());
 
        String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/JiaKaolog";
 
        File file = new File(dirPath, needDelFiel + MYLOGFILEName);// MYLOG_PATH_SDCARD_DIR
 
        if (file.exists()) {
 
            file.delete();
 
        }
 
    }
    private static long filesLength  = 0;
    public static void checkTotalFileSpace(){
        String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/JiaKaolog";
        String regx = "^[0-9]{4}-";
        Pattern pattern = Pattern.compile(regx);
        File file = new File(dirPath);
        filesLength = 0;
        if (file.isDirectory()) {
            File[] subFiles = file.listFiles();
            for (File f :
                    subFiles) {
                String fName = f.getName();
                if (!TextUtils.isEmpty(fName)) {
                    Matcher matcher = pattern.matcher(fName);
                    if (matcher.find()) {
                        Log.i(TAG, "文件名称:" + fName+"checkTotalFileSpace: "+f.length());
                        if (f.length()>20*1024*1024){
                            Log.i(TAG, "checkTotalFileSpace: 单个文件超过20MB ,删除"+f.getName());
                            f.delete();
                            continue;
                        }
                        filesLength +=f.length();
                    }
                }
            }
            if (filesLength >= 2*1024*1024){
                Log.i(TAG, "checkTotalFileSpace: 总大小超过20MB 删除"+filesLength+"B");
                delSubDirLogs();
            }
        }
    }
 
    public static void delSubDirLogs() {
        String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/JiaKaolog";
        String regx = "^[0-9]{4}-";
        Pattern pattern = Pattern.compile(regx);
        File file = new File(dirPath);
        boolean needDel = true;
        if (file.isDirectory()) {
 
            File[] subFiles = file.listFiles();
            for (File f :
                    subFiles) {
                String fName = f.getName();
 
                if (!TextUtils.isEmpty(fName)) {
                    Matcher matcher = pattern.matcher(fName);
                    if (matcher.find()) {
 
                        Log.i(TAG, "subDirLogs: 符合规则^[0-9]{4}- : " + matcher.group(0));
                        for (int i = 0; i < SDCARD_LOG_FILE_SAVE_DAYS; i++) {
                            String needSaveFileName = logfile.format(getDateBefore(i));
                            if (fName.contains(needSaveFileName)) {
                                Log.i(TAG, "delSubDirLogs: 此log需要保留:" + fName + " 日期:" + needSaveFileName);
                                needDel = false;
                                break;
                            } else {
                                needDel = true;
                            }
                        }
                        if (needDel) {
                            Log.i(TAG, "delSubDirLogs: 删除该文件:" + fName);
                            f.delete();
                        }
                    }
 
 
 
                } else {
                    Log.i(TAG, "delSubDirLogs: 不符合删除规则,则不删除:" + fName);
                }
            }
        } else {
            Log.i(TAG, "subDirLogs: is not a directory");
        }
 
    }
 
 
    /**
     * 得到现在时间前的几天日期,用来得到需要删除的日志文件名
     */
 
    private static Date getDateBefore() {
 
        Date nowtime = new Date();
 
        Calendar now = Calendar.getInstance();
 
        now.setTime(nowtime);
 
        now.set(Calendar.DATE, now.get(Calendar.DATE) - SDCARD_LOG_FILE_SAVE_DAYS);
 
        return now.getTime();
 
    }
 
    private static Date getDateBefore(int i) {
        Date nowtime = new Date();
 
        Calendar now = Calendar.getInstance();
 
        now.setTime(nowtime);
 
        now.set(Calendar.DATE, now.get(Calendar.DATE) - i);
 
        return now.getTime();
    }
 
}