lizhanwei
2020-07-28 c536e840b862977a0f71a7989481ba8032955607
lib/src/main/java/com/anyun/exam/lib/MyLog.java
@@ -25,12 +25,17 @@
        import java.text.SimpleDateFormat;
        import java.util.Calendar;
        import java.util.Date;
        import java.util.regex.Matcher;
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; // 日志文件总开关
@@ -42,9 +47,8 @@
    private static char MYLOG_TYPE = 'v';
    // 日志文件在sdcard中的路径
    private static String MYLOG_PATH_SDCARD_DIR = "/sdcard/JiaKaolog";
    private static int SDCARD_LOG_FILE_SAVE_DAYS = 3;// sd卡中日志文件的最多保存天数
    private static int SDCARD_LOG_FILE_SAVE_DAYS = 7;// sd卡中日志文件的最多保存天数
    private static String MYLOGFILEName = "Log.txt";// 本类输出的日志文件名称
@@ -172,14 +176,13 @@
            }
            if (MYLOG_WRITE_TO_FILE)//日志写入文件开关
                new Thread(new Runnable() {
                Executors.newSingleThreadExecutor().execute(new Runnable() {
                    @Override
                    public void run() {
                        writeLogtoFile(String.valueOf(level), tag, msg);
                        writeLogtoFile( tag, msg);
                    }
                }
                ).start();
                });
        }
@@ -235,7 +238,12 @@
        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();
@@ -258,6 +266,92 @@
        }
    }
    /**
     * 打开日志文件并写入日志
     *
     * @param tag
     * @param text
     */
    static int count=0;
    private static 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");
            Log.i(TAG,"tempFIle Name= "+tempFile.getName());
            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);
        }
    }
    /**
@@ -268,7 +362,7 @@
        String needDelFiel = logfile.format(getDateBefore());
        String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/nvlog";
        String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/JiaKaolog";
        File file = new File(dirPath, needDelFiel + MYLOGFILEName);// MYLOG_PATH_SDCARD_DIR
@@ -279,20 +373,51 @@
        }
    }
    public static void delSubDirLogs() {
        String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/jiakaolog";
    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);
        boolean needDel = false;
        filesLength = 0;
        if (file.isDirectory()) {
            Log.i(TAG, "subDirLogs: is a directory");
            File[] subFiles = file.listFiles();
            for (File f :
                    subFiles) {
                String fName = f.getName();
                Log.i(TAG, "subDirLogs: 文件名称:" + fName);
                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()) {
@@ -300,7 +425,6 @@
                        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));
                            Log.i(TAG,"needsaveFileName="+needSaveFileName);
                            if (fName.contains(needSaveFileName)) {
                                Log.i(TAG, "delSubDirLogs: 此log需要保留:" + fName + " 日期:" + needSaveFileName);
                                needDel = false;
@@ -313,16 +437,18 @@
                            Log.i(TAG, "delSubDirLogs: 删除该文件:" + fName);
                            f.delete();
                        }
                    } else {
                        Log.i(TAG, "delSubDirLogs: 不符合删除规则,则不删除:" + fName);
                    }
                } else {
                    Log.i(TAG, "delSubDirLogs: 不符合删除规则,则不删除:" + fName);
                }
            }
        } else {
            Log.i(TAG, "subDirLogs: is not a directory");
        }
    }