Android日志框架Logger修改默认缓存路径

android日志框架logger

https://github.com/orhanobut/logger

代码与分析

这里只针对性的分析磁盘缓存路径的修改,设置磁盘(SD卡)缓存的代码如下所示:

FormatStrategy formatStrategy = CsvFormatStrategy.newBuilder()
  .tag("custom")
  .build();
  
Logger.addLogAdapter(new DiskLogAdapter(formatStrategy));

其中CsvFormatStrategy为默认的文件格式化策略。

  @NonNull public CsvFormatStrategy build() {
      if (date == null) {
        date = new Date();
      }
      if (dateFormat == null) {
        dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss.SSS", Locale.UK);
      }
      if (logStrategy == null) {
        String diskPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        String folder = diskPath + File.separatorChar + "logger";

        HandlerThread ht = new HandlerThread("AndroidFileLogger." + folder);
        ht.start();
        Handler handler = new DiskLogStrategy.WriteHandler(ht.getLooper(), folder, MAX_BYTES);
        logStrategy = new DiskLogStrategy(handler);
      }
      return new CsvFormatStrategy(this);
    }

CsvFormatStrategy使用建造者模式创建实例,通过源码可以看到缓存路径是通过logStrategy 进行设置的,没有办法直接修改folder,可以考虑通过重写CsvFormatStrategy类进行修改,或者传入自己重写的DiskLogStrategy进行修改。修改过程中发现重写方案中,有些代码的作用域是受保护的,会导致要拷贝的类较多,所以考虑通过反射的方式,实现缓存路径的修改,代码如下:

  public static void init() {
        String diskPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        String folder = diskPath + File.separatorChar + "loggeraa";
        HandlerThread ht = new HandlerThread("AndroidFileLogger." + folder);
        ht.start();
        try {
            //通过反射实例化DiskLogStrategy中的内部类WriteHandler
            Class clazz = Class.forName("com.orhanobut.logger.DiskLogStrategy$WriteHandler");
            Constructor constructor = clazz.getDeclaredConstructor(Looper.class, String.class, int.class);
            //开启强制访问
            constructor.setAccessible(true);
            //核心:通过构造函数,传入相关属性,得到WriteHandler实例
            Handler handler = (Handler) constructor.newInstance(ht.getLooper(), folder, MAX_BYTES * 1024);
            //创建缓存策略
            FormatStrategy strategy = CsvFormatStrategy.newBuilder().logStrategy(new DiskLogStrategy(handler)).build();
            DiskLogAdapter adapter = new DiskLogAdapter(strategy);
            Logger.addLogAdapter(adapter);
        } catch (Exception e) {
            e.printStackTrace();
            ht.quit();
        }
    }

最终效果:

通过调试看到缓存策略的路径已经被修改为"/storage/emulated/0/loggeraa"


缓存路径修改

你可能感兴趣的:(Android日志框架Logger修改默认缓存路径)