Android获取Log信息所在的类名,方法名,行号。

本文介绍了一种在Android中自定义Log打印的方法,通过获取调用堆栈信息,自动记录打印信息的位置,包括方法名和行号,增强了日志的可读性和定位问题的能力。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * 获取打印信息所在方法名,行号等信息
 * @return
 */
private static String[] getAutoJumpLogInfos() {
    String[] infos = new String[] { "", "", "" };
    StackTraceElement[] elements = Thread.currentThread().getStackTrace();
    if (elements.length < 5) {
        Log.e("MyLogger", "Stack is too shallow!!!");
        return infos;
    } else {
        infos[0] = elements[4].getClassName().substring(
                elements[4].getClassName().lastIndexOf(".") + 1);
        infos[1] = elements[4].getMethodName() + "()";
        infos[2] = " at (" + elements[4].getClassName() + ".java:"
                + elements[4].getLineNumber() + ")";
        return infos;
    }
}

 

自定义Log:

public static void v(String msg){
    if (DEBUG){
        String[] infos = getAutoJumpLogInfos();
        android.util.Log.v(infos[0], msg + " : " + infos[1] + infos[2]);
    }else{
        //donothing
    }
}

public static void d(String msg){
    if (DEBUG){
        String[] infos = getAutoJumpLogInfos();
        android.util.Log.d(infos[0], msg + " : " + infos[1] + infos[2]);
    }else{
        //donothing
    }
}

public static void i(String msg){
    if (DEBUG){
        String[] infos = getAutoJumpLogInfos();
        android.util.Log.i(infos[0], msg + " : " + infos[1] + infos[2]);
    }else{
        //donothing
    }
}

public static void w(String msg){
    if (DEBUG){
        String[] infos = getAutoJumpLogInfos();
        android.util.Log.w(infos[0], msg + " : " + infos[1] + infos[2]);
    }else{
        //donothing
    }
}

public static void e(String msg){
    if (DEBUG){
        String[] infos = getAutoJumpLogInfos();
        android.util.Log.e(infos[0], msg + " : " + infos[1] + infos[2]);
    }else{
        //donothing
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值