AndroidStudio中使用Timber库如何自动添加函数名?
创始人
2024-08-21 05:30:15
0

在 Android Studio 中使用 Timber 日志库进行开发时,通常需要在每个日志输出处手动添加当前函数名,以便在日志中能够区别不同的输出。但是,这种手动添加函数名的方式显然十分麻烦,如果能够自动添加函数名,将会非常方便。

实现自动添加函数名的方法如下:

在 Timber 类中新增一个函数,用来获取当前函数名。这个函数可以通过 StackTraceElement 类的 getMethodName() 方法来获取:

private static String getFunctionName() {
    StackTraceElement[] sts = Thread.currentThread().getStackTrace();
    if (sts == null) {
        return null;
    }
    for (StackTraceElement st : sts) {
        if (st.isNativeMethod()) {
            continue;
        }
        if (st.getClassName().equals(Thread.class.getName())) {
            continue;
        }
        if (st.getClassName().equals(this.getClass().getName())) {
            continue;
        }
        return "["+Thread.currentThread().getName() + ":(" + st.getFileName() + ":" + st.getLineNumber() + "):" + st.getMethodName() + "]";
    }
    return null;
}

这个函数首先使用 Thread.currentThread().getStackTrace() 获取当前线程的调用栈,然后遍历调用栈中的每一个 StackTraceElement 对象,找到第一个非本地方法、非 Thread 类、非当前类的 StackTraceElement 对象,从中获取文件名、行号和方法名,并将其组合成一个字符串返回。这个返回的字符串就是当前函数的名称。

在 Timber 类中覆盖 log 方法,将组合好的函数名和日志信息一起输出:

@Override
protected void log(int priority, String tag, String message, Throwable t) {
    String functionName = getFunctionName();
    if (functionName != null) {
        message = functionName + " " + message;
    }
    super.log(priority, tag, message, t);
}

这个方法首先调用我们刚刚新增的 get

相关内容

热门资讯

透视关于"hhpok... 透视关于"hhpoker德州挂真的有吗"都是存在有辅助插件(哔哩哔哩)一、hhpoker德州挂真的有...
透视关于"pokem... 透视关于"pokemmo手机脚本辅助器"一贯有辅助方法(哔哩哔哩)1、玩家可以在pokemmo手机脚...
透视开挂"德扑之心免... 透视开挂"德扑之心免费透视"切实是有辅助工具(哔哩哔哩)1、点击下载安装,德扑之心免费透视脚本分类一...
透视解密"poker... 透视解密"poker辅助器免费安装"一贯是有辅助脚本(哔哩哔哩)poker辅助器免费安装是不是有人用...
透视有挂"epoke... 透视有挂"epoker透视"本来是有辅助插件(哔哩哔哩)1、epoker透视免费脚本咨询教程、epo...
透视了解"wepok... 透视了解"wepoker怎么破解游戏"本来存在有辅助技巧(哔哩哔哩)进入游戏-大厅左侧-新手福利-激...
透视教你"werpl... 透视教你"werplan怎么作必弊"一直是真的辅助攻略(哔哩哔哩)1)werplan怎么作必弊免费钻...
透视详细"wepok... 透视详细"wepoker辅助插件功能"一贯存在有辅助挂(哔哩哔哩)1、首先打开wepoker辅助插件...
透视辅助"aapok... 透视辅助"aapoker怎么开辅助器"原来存在有辅助软件(哔哩哔哩)aapoker怎么开辅助器脚本下...
透视透视"来玩app... 透视透视"来玩app 德州 辅助"好像是真的辅助技巧(哔哩哔哩)1、每一步都需要思考,不同水平的挑战...