解决Android Studio 3.1中使用Logger(com.orhanobut:logger:2.2.0)打印日志排版出现错乱的问题

先晒一张使用第三方Logger日志库打印日志出现排版错乱的情况的图片:

排版错乱原因:

The problem can be produce when trying to log message at very small time intervals, maybe some behavior of logcat has been changed in Android Studio v3.1, Android studio 3.1 is display based on milliseconds.

当尝试以非常小的时间间隔打印日志消息时,可能会产生这种问题,可能在Android StudioV3.1中更改了Logcat的某些行为,Android Studio 3.1是基于毫秒显示的。

解决方法:

首先自定义log strategy工具类

/**
 * 适用于com.orhanobut:logger:2.2.0或更新版本
 * @Description: 解决日志打印错位不整齐的问题
 * @Author: YinYongbo
 * @Time: 2018/7/25 11:27
 */
public class CustomLogCatStrategy implements LogStrategy {

    @Override
    public void log(int priority, @Nullable String tag, @NonNull String message) {
        Log.println(priority, randomKey() + tag, message);
    }

    private int last;

    private String randomKey() {
        int random = (int) (10 * Math.random());
        if (random == last) {
            random = (random + 1) % 10;
        }
        last = random;
        return String.valueOf(random);
    }
}

然后在初始化Logger的时候使用自定义的日志策略(.logStrategy(new CustomLogCatStrategy()))即可解决问题

FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
        .showThreadInfo(false)  // (Optional) Whether to show thread info or not. Default true
        .methodCount(1)         // (Optional) How many method line to show. Default 2
        .methodOffset(7)        // (Optional) Hides internal method calls up to offset. Default 5
        .logStrategy(new CustomLogCatStrategy()) // (Optional) Changes the log strategy to print out. Default LogCat
        .tag("yonbor605")   // (Optional) Global tag for every log. Default PRETTY_LOGGER
        .build();
Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy));

使用后的效果展示:

OK,完美解决,是不是看上去顺眼多了呢?

转载请注明出处,谢谢!

猜你喜欢

转载自blog.csdn.net/yonbor605/article/details/81200922