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

今天做了保存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");
               
            }
        }
    }

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,699评论 25 708
  • Ubuntu的发音 Ubuntu,源于非洲祖鲁人和科萨人的语言,发作 oo-boon-too 的音。了解发音是有意...
    萤火虫de梦阅读 99,628评论 9 467
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,573评论 0 17
  • 早就听说有个“无师课堂”的创举,今天一盆友发出一张截图,是他由“无师课堂”类推下去的:大意是往上是不是应该无校长,...
    凌宗伟阅读 725评论 2 1