更智能的println,显示堆栈中的深度

Hec*_*ret 1 java debugging

我在我的代码中使用System.out.println来跟踪程序的执行并获得一些有用的输出.这会在控制台中创建这样的结果:

Main function. Program starts.
Method getArea. Getting values
Method getSide. Side is 6
Method getArea. First value is 6
Method getSide. Side is 8
Method getArea. Second value is 8
Method getArea. Area is 48
Main function. The final area is 48
Run Code Online (Sandbox Code Playgroud)

我想创建tha方法,每次代码在方法调用堆栈中更深入时,都会在输出前面添加一个空格.例如,相同的代码,而不是使用System.out.println,现在使用Misc.smartPrintln:

Main function. Program starts.
 Method getArea. Getting values
  Method getSide. Side is 6
 Method getArea. First value is 6
  Method getSide. Side is 8
 Method getArea. Second value is 8
 Method getArea. Area is 48
Main function. The final area is 48
Run Code Online (Sandbox Code Playgroud)

该方法将具有以下定义:

public static void smartPrintln(String string);
Run Code Online (Sandbox Code Playgroud)

我不知道如何实现这个功能.任何想法如何解决这个问题?并且,使用记录器可以提供此功能吗?

ob1*_*ob1 5

创建一个临时的Throwable对象.使用其getStackTrace()方法分析堆栈并确定级别.例如

public static void smartPrintln(String string) {
    Throwable t = new Throwable();
    StackTraceElement[] stackElements = t.getStackTrace();
    int level = stackElements.length - 1; // don't forget our function adds a level
    for (int i = 0; i < level; i++) {
        System.out.print(' '); // could probably make this more efficient
    }
    System.out.println(string);
}
Run Code Online (Sandbox Code Playgroud)