Java 【基础】 模拟log4j,输出当前语句的行数,和类路径

一直很好奇log4j 是如何获取到当前输出的行数的,今天学到了,原来是堆栈跟踪,把代码贴出来给大家看一下。

    //模拟log4j
    public static void debug(String string){
    
    
        System.out.println("【调试】"+getStackTrace()[getStackTrace().length-1]+"\n"+string);
    }

    //获取当前调用此函数的所在的堆栈跟踪信息
    public static StackTraceElement[] getStackTrace(){
    
    
        StackTraceElement element[]=Thread.currentThread().getStackTrace();
        return  element;
    }

    //获取当前调用此函数的所在行数
    public static String getNowLine(){
    
    
        StackTraceElement element[]=Thread.currentThread().getStackTrace();
        String info[]= element[element.length-1].toString().split("\\.");
        return  info[info.length-1].replaceAll("[^\\d*]","");
    }

测试如下:注意这里文章的行数不是真的行数,具体为你代码里面的行数为准

    public static void main(String[] args) {
    
    
		//一般当前的类路径,和行数信息都在getStackTrace()数组的最后一个值。
        System.out.println("当前类路径:"+getStackTrace()[getStackTrace().length-1]);

        System.out.println("当前行数:"+getNowLine());

        debug("模拟log4j");
    }

输出如下:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_31254489/article/details/107722863