samedi 27 août 2016

Get the method name and class of the callee's previous call

I am working on generating profiling data at various points in my code. For this purpose I have written a profiler like this :

public static void startProfiler() {
    startLineNumber = getCallersLineNumber();
    start = System.currentTimeMillis();
}

public static void endProfiler() {
    end = System.currentTimeMillis();
    endLineNumber = getCallersLineNumber();
    int startPoint = Integer.parseInt(startLineNumber.split(":")[1]);
    long secs = (end - start) / 1000;
        LOG.info(startLineNumber.split(":")[0] + ":" + (startPoint + 1) + " " + secs);
    start = 0;
    end = 0;
}

public static String getCallersLineNumber() {
    StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
    String fullClassName = stacktrace[3].getClassName();
    String[] packageName = fullClassName.split("\\.");
    String className = packageName[packageName.length - 1];
    String methodName = stacktrace[3].getMethodName();
    int lineNumber = stacktrace[3].getLineNumber();
    return className + ":" + lineNumber;
}

This prints the name of the caller method's class and the lineNumber of the call.

Eg : For method in class

import xyz.abc;
class foo {
     public static foo() {
           abc a = new abc();
           startProfiler();
           a.getData();
           endProfiler();
     }
}

The output would be :

foo:6 10

I instead want it to print :

xyz.abc.getData() 10

This would mean I want the method name of the callee (class foo)'s call before the endProfiler was called (which is the method call a.getData()). Is this possible to get this using stacktraces/reflection or other means?





Aucun commentaire:

Enregistrer un commentaire