android: log android开发中怎么通过Log函数输出当前行号和当前函数名

本文介绍了一种在Android开发中使用Log函数输出当前行号和函数名的方法。通过创建Debug类,利用Exception的StackTrace特性,可以方便地获取并打印出这些调试信息,便于开发者追踪和定位问题。

android开发中怎么通过Log函数输出当前行号和当前函数名

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

public class Debug {

    public static int line(Exception e) {

        StackTraceElement[] trace = e.getStackTrace();

        if (trace == null || trace.length == 0)

            return -1; //

        return trace[0].getLineNumber();

    }

    public static String fun(Exception e) {

        StackTraceElement[] trace = e.getStackTrace();

        if (trace == null)

            return ""; //

        return trace[0].getMethodName();

    }

}

  使用场景:

1

2

3

4

5

6

7

8

public class test {

    public static String DI(Exception e) {

        return Debug.line(e)+"|"+Debug.fun(e)+"|";

    }

        public test() {

                 Log.d(TAG, DI(new Exception()));  //这里就输出我们需要的debug信息了

        }

}  

  

 另一种使用形式:

复制代码

 1 public class DebugInfo extends Exception {
 2     public int line() {
 3         StackTraceElement[] trace = getStackTrace();
 4         if (trace == null || trace.length == 0) {
 5             return -1;
 6         }
 7         return trace[0].getLineNumber();
 8     }
 9 
10     public String fun() {
11         StackTraceElement[] trace = getStackTrace();
12         if (trace == null || trace.length == 0) {
13             return "";
14         }
15         return trace[0].getMethodName();
16     }
17 
18     public DebugInfo() {
19         super();
20     }
21     
22     @Override
23     public String toString() {
24         return line() + "|" + fun() + "|";  
25     }
26 }

复制代码

使用方法

Log.d(TAG, new DebugInfo() + "hello world!");

 

复制代码

 1 public class DebugInfo {
 2     public static int line(StackTraceElement e) {
 3         return e.getLineNumber();
 4     }
 5 
 6     public static String method(StackTraceElement e) {
 7         return e.getMethodName();
 8     }
 9 
10     public static String info(StackTraceElement e) {
11         String ret = line(e) + "|" + method(e) + "|";
12         return ret;
13     }
14 }

复制代码

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值