Java [Basic] Simulate log4j, output the number of lines of the current statement, and the class path

I have always been curious about how log4j obtains the current number of output lines. I learned it today. It turned out to be a stack trace. Post the code for everyone to see.

    //模拟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*]","");
    }

The test is as follows: Note that the number of lines in this article is not the actual number of lines, the specific number of lines in your code shall prevail

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

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

        debug("模拟log4j");
    }

The output is as follows:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_31254489/article/details/107722863