美文网首页
安卓学习笔记------将log保存到本地

安卓学习笔记------将log保存到本地

作者: 天青色等烟雨hhft | 来源:发表于2017-11-29 18:11 被阅读0次

今天做了保存log到本地功能,防止App出现bug后不能及时查看log日志
首先封装了一个LogUtil类,以下是部分代码

自定义的前缀以及路径

 // 自定义Tag的前缀
    public static String customTagPrefix = "lxx";
    // 是否把保存日志到SD卡中
    private static final boolean isSaveLog = true;
    // SD卡中的根目录
    public static final String ROOT = Environment.getExternalStorageDirectory().getPath() + "/lxx/";
    private static final String PATH_LOG_INFO = ROOT + "info/";

自定义的logger


/**
     * 自定义的logger
     */
    public static CustomLogger customLogger;

    public interface CustomLogger {
        void e(String tag, String content)
    }

public static void e(String content) {
        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller);

        if (customLogger != null) {
            customLogger.e(tag, content);
        } else {
            Log.e(tag, content);
        }
        // isSaveLog是否把保存日志到SD卡中
        if (isSaveLog) {
            point(PATH_LOG_INFO, tag, content);
        }
    }

point方法,对文件夹以及文件的创建,写入做了对应的操作

public static void point(String path, String tag, String msg) {
        if (isSDAva()) {
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("",
                    Locale.SIMPLIFIED_CHINESE);
            dateFormat.applyPattern("yyyy");
            path = path + dateFormat.format(date) + "/";
            dateFormat.applyPattern("MM");
            path += dateFormat.format(date) + "/";
            dateFormat.applyPattern("dd");
            path += dateFormat.format(date) + ".log";
            dateFormat.applyPattern("[yyyy-MM-dd HH:mm:ss]");
            String time = dateFormat.format(date);
            File file = new File(path);
            if (!file.exists())
                createDipPath(path);
            BufferedWriter out = null;
            try {
                out = new BufferedWriter(new OutputStreamWriter(
                        new FileOutputStream(file, true)));
                out.write(time + " " + tag + " " + msg + "\r\n");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

createDipPath方法,根据文件路径,递归创建文件

 public static void createDipPath(String file) {
        String parentFile = file.substring(0, file.lastIndexOf("/"));
        File file1 = new File(file);
        File parent = new File(parentFile);
        if (!file1.exists()) {
            parent.mkdirs();
            try {
                file1.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

主要用到的就是以上代码
调用时直接调用LogUtils.e("需要保存的内容")即可保存到本地,比如:

 LogUtils.e("\n"+"登录时传的值-----------------"+
                                                "登陆类型:"+loginType+"\n"+
                                                "\n"+"用户名:"+userName+
                                                  "\n"+"密码"+pwd
                                                +"\n"+"身份"+getidentity());

安卓7.0对权限的访问是有问题的,所以需要动态申请权限,为了测试方便,只简单写了一下代码

public class MainActivity extends AppCompatActivity {

    // 要申请的权限
    private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 检查该权限是否已经获取
                  int i = ContextCompat.checkSelfPermission(this, permissions[0]);
                   // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                  if (i == PackageManager.PERMISSION_GRANTED) {
                          // 如果没有授予该权限,就去提示用户请求
//                           showDialogTipUserRequestPermission();
                      ActivityCompat.requestPermissions(this, permissions, 321);
                  }


    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
  
                    LogUtils.e("kkkkj");
               
            }
        }
    }

相关文章

网友评论

      本文标题:安卓学习笔记------将log保存到本地

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