android 自定义日志写入文件

版权声明:转载附上链接 https://blog.csdn.net/generallizhong/article/details/87936093

     上一篇我记录过是全局获取异常的日志写入文件中,便于查看查看全局获取异常日志,这篇主要是记录自定义需要记录的日志写入txt文本,比如:我们接口请求时总有意外,请求是否成功或者是否有返回的数据,避免与其他扯皮,我们就用日志记录下来,直接查看,当然最好是直接上传到后台服务,便于查看。最后会把Demo附上

主要类我已经封装好,可直接调用此类即可,下面是核心代码:

1、逻辑:记录一次开始时间,然后获取本机当前时间(最好开始时间与结束时间都获取服务器时间,因为如果把数据清掉就没有时间问题)对比两个时间是否超过多少天(比如7天),超过后删除文件,下次执行重新创建新文件。

   public static void write(final Object str) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SharedPreferences sharedPreferences = mContext.getSharedPreferences("oldTime", Context.MODE_PRIVATE);
                try {
                    String getoldtime = sharedPreferences.getString("oldtime", "");
                    Log.e("LZ----取出来来的时间getoldtime", getoldtime);
                    if (!getoldtime.isEmpty() || !getoldtime.equals("") || getoldtime != null) {
                        //转换开始时间对比
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        Date startdate = null;
                        try {
                            startdate = sdf.parse(getoldtime);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        if (getGapCount(startdate, MyDate.currentTime()) > 7) {//判断是否超过七天,如果超过则删除文件
                            Log.e("LZ----", "判断是是否超过七天");
                            File ff = getLogFile();
                            if ((!ff.exists()) || (!ff.isDirectory())) {
                                ff.delete();
                                SharedPreferences.Editor editor = sharedPreferences.edit();
                                editor.putString("oldtime", MyDate.getoldTime());
                                Log.e("LZ----oldtime", MyDate.getoldTime());
                                editor.commit();//提交修改
                            }

                        } else {
                            // 判断是否初始化或者初始化是否成功
                            if (null == mContext || null == instance || null == logFile || !logFile.exists()) {
                                Log.e(MY_TAG, "Initialization failure !!!");
                                return;
                            }
                            String logStr = getFunctionInfo() + " - " + str.toString();
                            Log.i(tag, logStr);

                            try {
                                BufferedWriter bw = new BufferedWriter(new FileWriter(logFile, true));
                                bw.write(logStr);
                                bw.write("UTF-8");
                                bw.write("\r\n");
                                bw.flush();
                            } catch (Exception e) {
                                Log.e(tag, "Write failure !!! " + e.toString());
                            }
                        }
                    } else {
                        SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
                        editor.putString("oldtime", MyDate.getoldTime());
                        Log.e("LZ----oldtime", MyDate.getoldTime());
                        editor.commit();//提交修改

                    }
                } catch (Exception e) {
                    SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
                    editor.putString("oldtime", MyDate.getoldTime());
                    editor.commit();//提交修改
                }
            }
        });

2、获取日志文件

private static File getLogFile() {
        File file;
        // 判断是否有SD卡或者外部存储器
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            // 有SD卡则使用SD - PS:没SD卡但是有外部存储器,会使用外部存储器
            // SD\Android\data\包名\files\Log\logs.txt
            file = new File(mContext.getExternalFilesDir("YSLog").getPath() + "/");
        } else {
            // 没有SD卡或者外部存储器,使用内部存储器
            // \data\data\包名\files\Log\logs.txt
            file = new File(mContext.getFilesDir().getPath() + "/YSLog/");
        }
        // 若目录不存在则创建目录
        if (!file.exists()) {
            file.mkdir();
        }
        File logFile = new File(file.getPath() + "/ys_logs.txt");
        if (!logFile.exists()) {
            try {
                logFile.createNewFile();
            } catch (Exception e) {
                Log.e(MY_TAG, "Create log file failure !!! " + e.toString());
            }
        }
        return logFile;
    }

3、对比两个时间相差时间天数

 public static int getGapCount(Date startDate, Date endDate) {
        Calendar fromCalendar = Calendar.getInstance();
        fromCalendar.setTime(startDate);
        fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
        fromCalendar.set(Calendar.MINUTE, 0);
        fromCalendar.set(Calendar.SECOND, 0);
        fromCalendar.set(Calendar.MILLISECOND, 0);

        Calendar toCalendar = Calendar.getInstance();
        toCalendar.setTime(endDate);
        toCalendar.set(Calendar.HOUR_OF_DAY, 0);
        toCalendar.set(Calendar.MINUTE, 0);
        toCalendar.set(Calendar.SECOND, 0);
        toCalendar.set(Calendar.MILLISECOND, 0);

        return (int) (toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24);

    }

需要看运行结果可下载Demo   Ps:这个是CSDN下载地址,需要积分,无法设置不要积分,我也很无奈

这是百度网盘下载了路径:Demo   Ps:无提取码

猜你喜欢

转载自blog.csdn.net/generallizhong/article/details/87936093