java打印函数的调用堆栈

Exception e = new Exception(“this is a log”); e.printStackTrace();
———————————
      StringBuilder sb=new StringBuilder(“”);
Exception e = new Exception(“hhhhhhhhhhhhhhhhhhh”);
StackTraceElement[] trace = e.getStackTrace();;
for (int i=0; i < trace.length; i++)
sb.append(“\tat ” + trace[i]);
logger.error(“who invoke me\n”+sb.toString());
—————————————-
source-code:
public class A {
public A() {}
private static void printStackTrace() {
        StackTraceElement[] stackElements = new Throwable().getStackTrace();
        if(stackElements != null)
        {
            for(int i = 0; i < stackElements.length; i++)
            {
                System.out.println(“”+ stackElements[i]); 
            }
        }
    }
    public void methodA() { methodB(); }
    public void methodB() { printStackTrace();}    
    
    public static void main(String[] argv) {
      A a = new A();
      a.methodA();
    }
  }
output:
A.printStackTrace(A.java:5)
A.methodB(A.java:16)
A.methodA(A.java:15)
A.main(A.java:20)
Note:
StackTraceElement.java
    public String toString() {
        return getClassName() + “.” + methodName +
            (isNativeMethod() ? “(Native Method)” :
             (fileName != null && lineNumber >= 0 ?
              “(” + fileName + “:” + lineNumber + “)” :
              (fileName != null ?  “(“+fileName+”)” : “(Unknown Source)”)));
    }
另外下面这些方法也可以:
new Exception(“hello”).printStackTrace();
Thread.getStackTrace()/Thread.getAllStackTraces() since jdk 1.5
Thread.currentThread().dumpStack()
参考资料:
2. jdk 1.7 Thread.java
   
    public StackTraceElement[] getStackTrace() {
        if (this != Thread.currentThread()) {
            // check for getStackTrace permission
            SecurityManager security = System.getSecurityManager();
            if (security != null) {
                security.checkPermission(
                    SecurityConstants.GET_STACK_TRACE_PERMISSION);
            }
            // optimization so we do not call into the vm for threads that
            // have not yet started or have terminated
            if (!isAlive()) {
                return EMPTY_STACK_TRACE;
            }
//Note:dumpThreads is a native method
            StackTraceElement[][] stackTraceArray = dumpThreads(new Thread[] {this});
            StackTraceElement[] stackTrace = stackTraceArray[0];
            // a thread that was alive during the previous isAlive call may have
            // since terminated, therefore not having a stacktrace.
            if (stackTrace == null) {
                stackTrace = EMPTY_STACK_TRACE;
            }
            return stackTrace;
        } else {
            // Don’t need JVM help for current thread
            return (new Exception()).getStackTrace();
        }
    }