1. 程式人生 > >儲存log.e日誌到本地

儲存log.e日誌到本地

 

package com.xvli.cit.Util;

import android.content.Context;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @param
 * @Comments : 網路請求日誌
 * @Author : Lampo
 * @ModifiedBy : Lampo
 */
public class HttpLogUtil {

    private static HttpLogUtil INSTANCE = null;
    private static String PATH_LOGCAT;
    private LogDumper mLogDumper = null;
    private File logFile;

    public static HttpLogUtil getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new HttpLogUtil();
        }
        return INSTANCE;
    }

    public void init(Context context) {
        PATH_LOGCAT = FileUtils.CreateFiles(context, "HttpLog");
        FileUtils.deleteExceedOneMonth(PATH_LOGCAT);
        if (mLogDumper == null) {
            mLogDumper = new LogDumper(String.valueOf(android.os.Process.myPid()), PATH_LOGCAT);
            mLogDumper.start();
        }
    }

    private class LogDumper extends Thread {

        private Process logcatProc;
        private BufferedReader mReader = null;
        String cmds = null;
        private String mPID;
        private FileOutputStream out = null;

        public LogDumper(String pid, String dir) {
            mPID = pid;
            try {
                logFile = FileUtils.createNewLogFile(dir);
                out = new FileOutputStream(logFile);
            } catch (Exception e) {
                e.printStackTrace();
            }

            /**
             *
             * 日誌等級:*:v , *:d , *:w , *:e , *:f , *:s
             *
             * 顯示當前mPID程式的 E和W等級的日誌.
             *
             * */

            // cmds = "logcat *:e *:w | grep \"(" + mPID + ")\"";
//             cmds = "logcat  | grep \"(" + mPID + ")\"";//列印所有日誌資訊
            // cmds = "logcat -s way";//列印標籤過濾資訊
//            cmds = "logcat *:e *:i *:d | grep \"(" + mPID + ")\"";
            //MrFu測試==============1
//            commandLine.clear();//清除所有的日誌
//            commandLine.add("logcat");
//            commandLine.add("-d");
//            commandLine.add("PDALog--->");

            //MrFu測試==============2
//            cmds = "logcat -f "+ logFile.getAbsolutePath() + " -v time *:V";//加上-f和後面的路徑【logFile.getAbsolutePath()】就會疊加列印所有到文字
//            cmds = "logcat -v time *:V";//只儲存當前的到日誌
//            cmds = "logcat -s PDALog--->";//打印出Tag為“PDALog--->”的日誌
            cmds = "logcat -v time -s PDALog--->";//打印出Tag為“PDALog--->”的日誌


        }

        @Override
        public void run() {
            try {
                logcatProc = Runtime.getRuntime().exec(cmds);
                mReader = new BufferedReader(new InputStreamReader(logcatProc.getInputStream()), 1024);
                String line = null;
                while ((line = mReader.readLine()) != null) {
                    if (line.length() == 0) {
                        continue;
                    }
                    if (out != null && line.contains(mPID)) {
                        out.write((Util.getNowDate_All() + "\r\n" + line + "\r\n").getBytes());
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (logcatProc != null) {
                    logcatProc.destroy();
                    logcatProc = null;
                }
                if (mReader != null) {
                    try {
                        mReader.close();
                        mReader = null;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    out = null;
                }
            }
        }
    }
}

  /**
     * 在Cit資料夾下建立新的子資料夾
     *
     * @param context
     * @param fileName
     * @return
     */
    public static String CreateFiles(Context context, String fileName) {
        String PATH_LOGCAT;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {// 優先儲存到SD卡中
            PATH_LOGCAT = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + Config.APP_NAME + "/" + fileName;
        } else {// 如果SD卡不存在,就儲存到本應用的目錄下
            PATH_LOGCAT = context.getFilesDir().getAbsolutePath() + File.separator + Config.APP_NAME + "/" + fileName;
        }
        File file = new File(PATH_LOGCAT);
        if (!file.exists()) {
            file.mkdirs();
        }
        return PATH_LOGCAT;
    }


  /**
     * 刪除超過一個月的log
     *
     * @param path 資料夾名稱
     */
    public static void deleteExceedOneMonth(String path) {
        File file1 = new File(path);
        File[] files = file1.listFiles();
        if (files.length <= 30) {
            return;
        }
        for (int i = 0; i < files.length; i++) {
            String str = files[i].getName().replace(".log", "").replace("CIT-", "");
            if (str.indexOf("U") != -1) {
                str = str.replace("-U", "");
            }
            if (!Util.isExceedOneMonth(str)) {
                deleteFile(path + "/" + files[i].getName());
            }
        }
    }


    /**
     * 是否是30天內
     *
     * @param month
     * @return
     * @throws ParseException
     */
    public static boolean isExceedOneMonth(String month) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        long day = 0;
        try {
            date = df.parse(month + " 00:00:00");
            long time = date.getTime();
            Date now = df1.parse(getNowDate());
            long nowTime = now.getTime();
            day = (nowTime - time) / (24 * 60 * 60 * 1000);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (day <= 30) {
            return true;
        } else {
            return false;
        }
    }



 /**
     * 單個刪除檔案
     *
     * @param path
     */
    public static void deleteFile(String path) {
        File file = new File(path);
        if (file.exists() && file.isFile()) {//是否可以在該檔案中找到該檔案//該檔案是否表示底層上
            PDALogger.e("file.isFile  true");
            file.delete();
        }
    }