美文网首页
打印 log 到本地 SDcard

打印 log 到本地 SDcard

作者: that_is_this | 来源:发表于2018-01-05 14:13 被阅读49次
private static void log(String tag, String msg, 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)
            writeLogtoFile(String.valueOf(level), tag, msg);
    }
}

private static void writeLogtoFile(String mylogtype, String tag, String text) {   // 新建或打开日志文件
    Date nowtime = new Date();
    int pid = Process.myPid();
    String needWriteFiel = logfile.format(nowtime);
    String needWriteMessage = myLogSdf.format(nowtime) + "   " + pid + "    " + mylogtype + "  " + tag + "  " + text;
    File file = new File(MYLOG_PATH_SDCARD_DIR, needWriteFiel + MYLOGFILEName);
    try {
        FileWriter filerWriter = new FileWriter(file, true);            // 后面这个参数代表是不是要接上文件中原来的数据,不进行覆盖
        BufferedWriter bufWriter = new BufferedWriter(filerWriter);
        bufWriter.write(needWriteMessage);
        bufWriter.newLine();
        bufWriter.close();
        filerWriter.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public static void delFile() {// 删除日志文件
    String needDelFiel = logfile.format(getDateBefore());
    File file = new File(MYLOG_PATH_SDCARD_DIR, needDelFiel + MYLOGFILEName);
    if (file.exists()) {
        file.delete();
    }
}

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();
}

相关文章

网友评论

      本文标题:打印 log 到本地 SDcard

      本文链接:https://www.haomeiwen.com/subject/mixsnxtx.html