功能强大的Log工具

最近从github上面看到一个非常强大的android开发工具,Logger,其 github 地址如下:https://github.com/orhanobut/logger ,下面介绍一下这个工具的用法,以便于自己开发使用的时候取用。

第一步,在 app 的 gradle 中建立依赖,gradle 会自动下载编译,其对应的rar包可以在文件夹中找到

    implementation 'com.orhanobut:logger:2.2.0'

第二步,在 MainActivity 中初始化 Logger 的适配器,其中 BuildConfig.IsLogShow 是我在 gradle 中设置的全局变量,用于控制 Log 信息是否显示

   private void initLogger() {
        Logger.addLogAdapter(new AndroidLogAdapter(){
            @Override
            public boolean isLoggable(int priority, @Nullable String tag) {
                return BuildConfig.IsLogShow;
            }
        });
    }

需要注意的是,导入包的名称如下:

import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;

接下来就只可以直接使用 Logger 进行操作了,当然你也可以对 Logger 进行一些个性化设置,通过如下配置:

FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
  .showThreadInfo(false)  // (Optional) 是否显示线程信息,默认为 true
  .methodCount(0)         // (Optional) 要显示多少个方法行,默认为 2
  .methodOffset(7)        // (Optional) Hides internal method calls up to offset. Default 5
  .logStrategy(customLog) // (Optional) Changes the log strategy to print out. Default LogCat
  .tag("MyTag")   // (Optional) 设置全局标记(Tag),默认 Tag 为 PRETTY_LOGGER
  .build();

Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy));

第三步,Logger 的使用方式入下:

  • 打印字符串:

    Logger.d("hello");
    
  • 支持设置打印字符串的格式:

    Logger.d("hello %s", "world");
    
  • 支持以下打印方式(只在 debug 模式可用):

    Logger.d(MAP);          //打印 Map 对象
    Logger.d(SET);           //打印 Set 对象
    Logger.d(LIST);
    Logger.d(ARRAY);
    Logger.json(JSON);
    Logger.xml(XML);
    
  • 支持将 Log 信息存储为本地文件:

    Logger.addLogAdapter(new DiskLogAdapter());
    
  • 支持将 Log 信息存储为本地文件前,为其添加自定义标签 Tag:

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

我不理解的地方

  • 其中,customLog我还不知道怎么来的,后面了解后更新
  • Readme 中提到的 Timber Integration , 代码如下:

    // Set methodOffset to 5 in order to hide internal method calls
    Timber.plant(new Timber.DebugTree() {
      @Override protected void log(int priority, String tag, String message, Throwable t) {
        Logger.log(priority, tag, message, t);
      }
    });
    

猜你喜欢

转载自blog.csdn.net/baidu_33221362/article/details/79874803