新架构文档

日志类HFLogger介绍

Inspired by orhanobut's logger and JakeWharton's timber

1)初始化和释放

在第三方app的Application类的onCreate函数中进行日志树的初始化操作,可以种植多棵日志树,默认提供了三种类型的日志树:HFLogcatTree,HFFileTree和HFHollowTree,HFLogcatTree用于把日志打印到logcat中,HFFileTree用于把日志打印到文件中(目前为空实现,看是否有应用场景),HFHollowTree也是空实现,提供给调用者继承,从而实现自己的日志树(例如用于异常和Crash日志上报等)。

初始化代码如下:

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        if (BuildConfig.DEBUG) {
            // 实例化logcat日志树,并对其进行自定义设置
            HFLogcatTree logcatTree = new HFLogcatTree();
            logcatTree.init().setMethodCount(1); // 设置显示的函数调用层级为1

            // 种植logcat日志树
            HFLogger.plant(logcatTree);
        } else {
            HFLogger.plant(new CrashReportingTree());
        }

    }

}

释放的代码可以根据各个app的具体实现,只要保证放在app退出的时候调用即可,例如如果app是在MainActivity的onDesroy函数中退出时,调用代码如下:

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (BuildConfig.DEBUG) {
            HFLogger.uproot(new HFLogcatTree());
        } else {
            HFLogger.uproot(new CrashReportingTree());
        }

        // 如果种植了多棵日志树,那么可以使用 HFLogger.uprootAll()一次性移除
    }

2)日志记录

经过1)所示的初始化操作之后,就可以在app全局调用HFLogger提供的各种级别日志记录功能。

注意,查看logcat时要确保不要打开logcat的自动换行功能(use soft wraps):

2.1)格式1

HFLogger.d("我认为全球市场可能需要五台计算机。");

在logcat中输出结果为:

2.2)格式2

HFLogger.d("我认为全球市场可能需要五台计算机。", 3);

在logcat中输出结果为:

2.3)格式3

HFLogger.d("PAIC", "我认为全球市场可能需要五台计算机。");

在logcat中输出结果为:

2.4)格式4

HFLogger.d("PAIC", "我认为全球市场可能需要五台计算机。", 4);

在logcat中输出结果为:

2.5)格式5

try {
    Class clazz = Class.forName("NotExistClassName");
} catch (ClassNotFoundException e) {
    HFLogger.e(e);
}

在logcat中输出结果为:

2.6)格式6

static final String JSON_CONTENT = "{\"widget\": {" +
            "    \"debug\": \"on\"," +
            "    \"window\": {" +
            "        \"title\": \"Sample HFLogger Widget\"," +
            "        \"name\": \"main_window\"," +
            "        \"width\": 500," +
            "        \"height\": 500" +
            "    },\n" +
            "    \"image\": { " +
            "        \"src\": \"Images/Sun.png\"," +
            "        \"name\": \"sun1\"," +
            "        \"hOffset\": 250," +
            "        \"vOffset\": 250," +
            "        \"alignment\": \"center\"" +
            "    },\n" +
            "    \"text\": {" +
            "        \"data\": \"Click Here\"," +
            "        \"size\": 36," +
            "        \"style\": \"bold\"," +
            "        \"name\": \"text1\"," +
            "        \"hOffset\": 250," +
            "        \"vOffset\": 100," +
            "        \"alignment\": \"center\"," +
            "        \"onMouseUp\": \"sun1.opacity = (sun1.opacity / 100) * 90;\"" +
            "    }" +
            "}}    ";
HFLogger.json(JSON_CONTENT);

在logcat中输出结果为: