Android 本地日志保存

Android 本地日志保存

下面介绍一个本地日志保存的工具类,当然需要先获取到文件存储权限
没啥说的,直接上代码吧

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by Administrator on 2018\12\12 0012.
 */

public class WriteLogSDCard {

    private static final String FOLDER_NAME="日志文件夹名称";
    private static final String FILE_NAME="日志文件名称";
    private static volatile Context sContext;

    private static String packageName = "";

    static HnLogLinkedBlockingDeque<String> logDeque = new HnLogLinkedBlockingDeque<String>(15000);

    private static final int[] INTERVAL_RETRY_INIT = new int[]{1, 2, 4, 8, 16, 29}; //重试时间

    private static AtomicInteger retryInitTimes = new AtomicInteger(0);

    public static final SimpleDateFormat timeFormatter = new SimpleDateFormat("yy-MM-dd HH:mm:ss");

    private static String logTime = "";

    private static String logPath = "";

   public static String nowUsedFile = "";

    static final ReentrantLock lock = new ReentrantLock();

    protected static Object formatterLock = new Object();

    private static long nextDayTime;

    private static long nextSecondMinuteTime;

    static long lastWriterErrorTime = 0;

    private static boolean bActive = true;

    private static FileWriter writer;

    private static Handler retryInitHandler = new Handler(Looper.getMainLooper());


    /**
     * 初始化日志
     */
    public static void init(Context context) {
        sContext = context;
        initRunnable.run();
    }

    /**
     * 将日志写到文件
     */
    private static void writeLogToFile(String log) {
        try {
            // 如果SD卡不可用,则不写日志,以免每次都抛出异常,影响性能
            if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                System.out.println("writeLogToFile not ready");
                return;
            }

            if (null == writer) {
                System.out.println("can not write SxbLog.");
                long now = System.currentTimeMillis();
                if (lastWriterErrorTime == 0) {
                    lastWriterErrorTime = now;
                } else if (now - lastWriterErrorTime > 60 * 1000) {
                    try {
                        initLogFile(System.currentTimeMillis());
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    lastWriterErrorTime = now;
                }
            } else {
                long now = System.currentTimeMillis();
                if (now > nextDayTime) {
                    initLogFile(now);
                }
                //加入消息的时候记录时间
                if (lock.tryLock()) {
                    try {
                        writer.write(log);
                        writer.flush();
                    } finally {
                        lock.unlock();
                    }
                } else {
                    if (!insertLogToCacheHead(log)) {
                        System.out.println("insertLogToCacheHead failed!");
                    }
                }
            }

        } catch (Throwable e) {
            if (e instanceof IOException && e.getMessage().contains("ENOSPC")) {
                e.printStackTrace();
            } else {
                try {
                    initLogFile(System.currentTimeMillis());
                } catch (Throwable e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 写日志线程
     */
    static Thread takeThread = new Thread() {
        public void run() {
            while (bActive) {
                synchronized (this) {
                    try {
                        String log;
                        log = logDeque.take();
                        if (null != log) {
                            writeLogToFile(log);
                        }
                    } catch (Exception e) {
                        System.out.println("write log file error: " + e.toString());
                    } catch (AssertionError ignore) {
                        System.out.println("--------------");
                    }
                }
            }
        }
    };

    private static String getDateStr(long nowCurrentMillis) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(nowCurrentMillis);
        SimpleDateFormat logFileFormatter = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat timeFormatter = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
        logTime = timeFormatter.format(nowCurrentMillis);
        String thisLogName = logFileFormatter.format(calendar.getTime());
        setNextSecond(calendar);
        setNextHour(calendar);
        return thisLogName;
    }

    private static void setNextHour(Calendar setSecondedCalendar) {
        setSecondedCalendar.add(Calendar.DAY_OF_MONTH, 1);
        nextDayTime = setSecondedCalendar.getTimeInMillis();
    }

    private static void setNextSecond(Calendar calendar) {
        calendar.set(Calendar.MILLISECOND, 0);
        nextSecondMinuteTime = calendar.getTimeInMillis() + 1000;
    }

    public static String getLogFileName(String dataStr) {
        return FILE_NAME + dataStr + ".log";
    }

    private static synchronized void checkNextMinuteTime(long currentTimeMillis) {
        if (currentTimeMillis > nextSecondMinuteTime) {
            synchronized (formatterLock) {
                logTime = timeFormatter.format(currentTimeMillis);
                nextSecondMinuteTime = nextSecondMinuteTime + 1000;
            }
        }
    }


    /**
     * 初始化日志文件
     */
    static synchronized void initLogFile(long nowCurrentTimeMillis) throws IOException {
        logPath = Environment.getExternalStorageDirectory().getPath() + "/"+FOLDER_NAME+"/" + packageName.replace(".", "/") + "/";
        File tmpeFile = new File(logPath);
        if (!tmpeFile.exists()) {
            tmpeFile.mkdirs();
        }
        nowUsedFile = logPath + getLogFileName(getDateStr(nowCurrentTimeMillis));
        try {
            tmpeFile = new File(nowUsedFile);
            if (!tmpeFile.exists()) {
                boolean b = tmpeFile.createNewFile();
                if (null != writer) {
                    writer.write(logTime + "|" + "|D|" + android.os.Build.MODEL + " " + android.os.Build.VERSION.RELEASE + " create newLogFile " + tmpeFile.getName() + " " + b + "\n");
                    writer.flush();
                }
            } else {
                if (null != writer) {
                    writer.write(logTime + "|" + "|E|" + android.os.Build.MODEL + " " + android.os.Build.VERSION.RELEASE + "|newLogFile " + tmpeFile.getName() + " is existed.\n");
                    writer.flush();
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        writer = new FileWriter(tmpeFile, true);
    }

    static void delete7DaysBeforeFiles(long today) {
        logPath = Environment.getExternalStorageDirectory().getPath() + "/"+FOLDER_NAME+"/" + packageName.replace(".", "/");
        long day = (long) 1 * 24 * 60 * 60 * 1000;
        File tmpeFile;
        //删除前一个月的
        for (long i = (today - 7 * day); i > today - 37 * day; i = i - day) {
            String date = getDateStr(i);
            nowUsedFile = logPath + getLogFileName(date);
            try {
//                Log.i("logtest", "find file: " + getLogFileName(date));
                tmpeFile = new File(nowUsedFile);
                if (tmpeFile.exists()) {
//                    Log.e("logtest", date + " tmpFile exists" + " delete ");
                    tmpeFile.delete();
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 日志初始化Runnable
     */
    public static Runnable initRunnable = new Runnable() {
        @Override
        public void run() {
            if (null == sContext) {
                return;
            }

            new Thread("LVBLogInitThread") {
                @Override
                public void run() {
                    try {
                        try {
                            packageName = sContext.getPackageName();
                        } catch (Exception e) {
                            packageName = "unknown";
                        }
                        delete7DaysBeforeFiles(System.currentTimeMillis());
                        initLogFile(System.currentTimeMillis());

                        if (!takeThread.isAlive()) {
                            takeThread.setName("logWriteThread");
                            takeThread.start();
                        }
                        retryInitHandler.removeCallbacks(initRunnable);
                    } catch (Exception e) {
                        int times = retryInitTimes.get();
                        System.out.println("ILVBLog init post retry " + times + " times, interval " + INTERVAL_RETRY_INIT[times]);
                        retryInitHandler.removeCallbacks(initRunnable);
                        retryInitHandler.postDelayed(initRunnable, INTERVAL_RETRY_INIT[times] * 60000);
                        times++;
                        if (times >= INTERVAL_RETRY_INIT.length) {
                            times = 0;
                        }
                        retryInitTimes.set(times);
                    }
                }
            }.start();
        }
    };

    public static void writeLog(String TAG, String msg, Throwable tr) {
        long now = System.currentTimeMillis();
        if (now >= nextSecondMinuteTime) {
            checkNextMinuteTime(now);
        }
      
        String message = "[" + logTime + "]" + TAG + ":" + msg + "\n";
        if (null != tr) {
            message = "[" + logTime + "]" + TAG + ":" + msg + "\n" + android.util.Log.getStackTraceString(tr) + "\n";
        }
        addLogToCache(message);
    }

    /**
     * 添加日志到缓存
     */
    private static boolean addLogToCache(String log) {
        try {
            logDeque.add(log);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 添加缓冲头部
     */
    private static boolean insertLogToCacheHead(String log) {
        try {
            logDeque.addFirst(log);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static void pauseLogThread() {
        bActive = false;
        writeLog("pauseLogThread", "pauseLogThread->enter", null);
    }

    public static void resumeLogThread() {
        bActive = true;
        retryInitHandler.postDelayed(initRunnable, 0);
    }
}

当然还是免不了要初始化的

WriteLogSDCard.init(HnApplication.getContext());

初始化之后只需要很简单的调用就好了

 WriteLogSDCard.writeLog("房间定时器--Activity", "关闭", Throwable);
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335