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

相关内容

热门资讯

透视新版!hhpoker真的假... 透视新版!hhpoker真的假的,newpoker怎么安装脚本,机巧教程(有挂方法)-哔哩哔哩new...
透视工具!wepoker怎么破... 透视工具!wepoker怎么破解游戏,wepoker高级辅助,阶段教程(了解有挂)-哔哩哔哩wepo...
透视教程!aapoker怎么选... 透视教程!aapoker怎么选牌,德州hhpoker脚本,演示教程(存在有挂)-哔哩哔哩1、点击下载...
透视辅助!德州局怎么透视,aa... 透视辅助!德州局怎么透视,aapoker ai插件,模板教程(有挂辅助)-哔哩哔哩1、很好的工具软件...
透视肯定!wpk透视是真的假的... 透视肯定!wpk透视是真的假的,德州局怎么透视,窍要教程(的确有挂)-哔哩哔哩1、wpk透视是真的假...
透视智能ai!wepokerp... 透视智能ai!wepokerplus脚本,wepoker怎么获得好牌,攻略教程(有挂技巧)-哔哩哔哩...
透视系统!德州局透视脚本下载安... 透视系统!德州局透视脚本下载安装最新版本,wpk安卓下载辅助,课程教程(有挂教学)-哔哩哔哩1、下载...
透视辅助!德普之星透视辅助软件... 透视辅助!德普之星透视辅助软件是真的吗,wepoker底牌透视,妙计教程(有挂方针)-哔哩哔哩1、这...
透视真的!hhpoker辅助靠... 透视真的!hhpoker辅助靠谱吗,pokerworld破解版下载,讲义教程(有挂方针)-哔哩哔哩1...
透视脚本!aapoker辅助工... 透视脚本!aapoker辅助工具安全吗,hhpoker视频巡查真的假的,练习教程(揭秘有挂)-哔哩哔...