Example usage for java.lang StackTraceElement getMethodName

List of usage examples for java.lang StackTraceElement getMethodName

Introduction

In this page you can find the example usage for java.lang StackTraceElement getMethodName.

Prototype

public String getMethodName() 

Source Link

Document

Returns the name of the method containing the execution point represented by this stack trace element.

Usage

From source file:org.eclipse.swt.examples.watchdog.TimedEventWatchdog.java

private static boolean traceElementIs(StackTraceElement e, String className, String method) {
    return className.equals(e.getClassName()) && method.equals(e.getMethodName());
}

From source file:com.moss.greenshell.wizard.catastrophe.PostMortemScreen.java

public static void submitErrorReport(final Throwable cause, final ErrorReportDecorator... decorators)
        throws Exception {

    List<ErrorReportChunk> chunks = new LinkedList<ErrorReportChunk>();

    try {/* ww  w  .j a va2 s.com*/
        if (cause instanceof InternalErrorException) {
            InternalErrorException ie = (InternalErrorException) cause;
            ErrorReportChunk chunk = new ErrorReportChunk("internal-error-id", "text/plain",
                    ie.id().getBytes("UTF8"));
            chunks.add(chunk);
        } else if (cause instanceof SOAPFaultException) {
            SOAPFaultException soapFault = (SOAPFaultException) cause;
            String content = soapFault.getFault().getFirstChild().getTextContent();
            String prefix = "Internal Service Error Occurred: ";
            if (content.startsWith(prefix)) {
                String id = content.substring(prefix.length());
                ErrorReportChunk chunk = new ErrorReportChunk("internal-error-id", "text/plain",
                        id.getBytes("UTF8"));
                chunks.add(chunk);
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }

    // STACK TRACE
    ByteArrayOutputStream stackBytes = new ByteArrayOutputStream();
    PrintStream stackPrintStream = new PrintStream(stackBytes);
    cause.printStackTrace(stackPrintStream);
    stackPrintStream.close();
    stackBytes.close();

    ErrorReportChunk chunk = new ErrorReportChunk("stack trace", "text/plain", stackBytes.toByteArray());
    chunks.add(chunk);

    // THREAD DUMP

    ByteArrayOutputStream dumpBytes = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(dumpBytes);
    Map<Thread, StackTraceElement[]> traceMap = Thread.getAllStackTraces();
    for (Map.Entry<Thread, StackTraceElement[]> next : traceMap.entrySet()) {
        out.println();
        out.println(next.getKey().getName());
        for (StackTraceElement line : next.getValue()) {
            String className = emptyIfNull(line.getClassName());
            String methodName = emptyIfNull(line.getMethodName());
            String fileName = emptyIfNull(line.getFileName());

            out.println("    " + className + "." + methodName + " (" + fileName + " line "
                    + line.getLineNumber() + ")");
        }
    }
    out.flush();
    out.close();
    ErrorReportChunk stackDump = new ErrorReportChunk("thread dump", "text/plain", dumpBytes.toByteArray());
    chunks.add(stackDump);

    // SYSTEM PROPERTIES
    ByteArrayOutputStream propsBytes = new ByteArrayOutputStream();
    PrintStream propsOut = new PrintStream(propsBytes);
    for (Map.Entry<Object, Object> next : System.getProperties().entrySet()) {
        propsOut.println(" " + next.getKey() + "=" + next.getValue());
    }
    propsOut.flush();
    propsOut.close();
    chunks.add(new ErrorReportChunk("system properties", "text/plain", propsBytes.toByteArray()));

    // LOCAL CLOCK
    chunks.add(new ErrorReportChunk("local clock", "text/plain", new DateTime().toString().getBytes()));

    // NETWORKING
    StringBuffer networking = new StringBuffer();
    Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
    while (ifaces.hasMoreElements()) {
        NetworkInterface iface = ifaces.nextElement();
        networking.append("INTERFACE: " + iface.getName() + " (" + iface.getDisplayName() + ")\n");
        Enumeration<InetAddress> addresses = iface.getInetAddresses();
        while (addresses.hasMoreElements()) {
            InetAddress address = addresses.nextElement();
            networking.append("  Address:" + address.getHostAddress() + "\n");
            networking.append("      Cannonical Host Name: " + address.getCanonicalHostName() + "\n");
            networking.append("                 Host Name: " + address.getHostName() + "\n");
        }
    }
    chunks.add(new ErrorReportChunk("network configuration", "text/plain", networking.toString().getBytes()));

    // DECORATORS
    if (decorators != null) {
        for (ErrorReportDecorator decorator : decorators) {
            chunks.addAll(decorator.makeChunks(cause));
        }
    }
    ErrorReport report = new ErrorReport(chunks);
    Reporter reporter = new Reporter();
    ReportId id = reporter.submitReport(report);
}

From source file:org.glowroot.agent.impl.BytecodeServiceImpl.java

private static boolean ignoreMainClass(String expectedTopLevelClass, String expectedTopLevelMethodName,
        StackTraceElement[] stackTrace) {
    if (stackTrace.length == 0) {
        return true;
    }/*  w w w  .j  av a2s  .  c o  m*/
    StackTraceElement topStackTraceElement = stackTrace[stackTrace.length - 1];
    return !topStackTraceElement.getClassName().equals(expectedTopLevelClass)
            || !expectedTopLevelMethodName.equals(topStackTraceElement.getMethodName());
}

From source file:kilim.Fiber.java

static void ds() {
    for (StackTraceElement ste : new Exception().getStackTrace()) {
        String cl = ste.getClassName();
        String meth = ste.getMethodName();
        if (cl.startsWith("kilim.Worker") || meth.equals("go") || meth.equals("ds"))
            continue;
        String line = ste.getLineNumber() < 0 ? "" : ":" + ste.getLineNumber();
        log.info('\t' + cl + '.' + ste.getMethodName() + '(' + ste.getFileName() + line + ')');
    }/*from   w  ww.jav  a2 s.c o m*/
}

From source file:com.hellofyc.base.net.http.HttpUtils.java

private static void getInvokeStackTraceElement() {
    FLog.i("Thread ID: " + Thread.currentThread().getId() + " getInvokeStackTraceElement");
    StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
    for (StackTraceElement element : stackTraceElements) {
        FLog.i("(" + element.getLineNumber() + ") " + "class name:" + element.getClassName() + ", method name:"
                + element.getMethodName());
    }//w ww.  j a  v a  2  s.  co m
}

From source file:org.apache.samza.logging.log4j2.serializers.LoggingEventJsonSerde.java

/**
 * Encodes a LoggingEvent into a HashMap using the logstash JSON format.
 *
 * @param loggingEvent/*w  ww.  ja va2  s .c  om*/
 *          The LoggingEvent to encode.
 * @param includeLocationInfo
 *          Whether to include LocationInfo in the map, or not.
 * @return A Map representing the LoggingEvent, which is suitable to be
 *         serialized by a JSON encoder such as Jackson.
 */
@SuppressWarnings("rawtypes")
public static Map<String, Object> encodeToMap(LogEvent loggingEvent, boolean includeLocationInfo) {
    Map<String, Object> logstashEvent = new LoggingEventJsonSerde.LoggingEventMap();
    String threadName = loggingEvent.getThreadName();
    long timestamp = loggingEvent.getTimeMillis();
    HashMap<String, Object> exceptionInformation = new HashMap<String, Object>();
    Map mdc = loggingEvent.getContextData().toMap();
    ThreadContext.ContextStack ndc = loggingEvent.getContextStack();

    logstashEvent.put("@version", VERSION);
    logstashEvent.put("@timestamp", dateFormat(timestamp));
    logstashEvent.put("source_host", getHostname());
    logstashEvent.put("message", loggingEvent.getMessage());

    if (loggingEvent.getThrown() != null) {
        final Throwable throwableInformation = loggingEvent.getThrown();
        if (throwableInformation.getClass().getCanonicalName() != null) {
            exceptionInformation.put("exception_class", throwableInformation.getClass().getCanonicalName());
        }
        if (throwableInformation.getMessage() != null) {
            exceptionInformation.put("exception_message", throwableInformation.getMessage());
        }
        if (throwableInformation.getMessage() != null) {
            StringBuilder stackTrace = new StringBuilder(ExceptionUtils.getStackTrace(throwableInformation));
            exceptionInformation.put("stacktrace", stackTrace);
        }
        logstashEvent.put("exception", exceptionInformation);
    }

    if (includeLocationInfo) {
        StackTraceElement info = loggingEvent.getSource();
        logstashEvent.put("file", info.getFileName());
        logstashEvent.put("line_number", info.getLineNumber());
        logstashEvent.put("class", info.getClassName());
        logstashEvent.put("method", info.getMethodName());
    }

    logstashEvent.put("logger_name", loggingEvent.getLoggerName());
    logstashEvent.put("mdc", mdc);
    logstashEvent.put("ndc", ndc);
    logstashEvent.put("level", loggingEvent.getLevel().toString());
    logstashEvent.put("thread_name", threadName);

    return logstashEvent;
}

From source file:org.kei.android.phone.cellhistory.CellHistoryApp.java

@SuppressWarnings("unchecked")
public static void addLog(final Context c, final Object msg) {
    final CellHistoryApp ctx = CellHistoryApp.getApp(c);
    ctx.lock();/*from   ww w.  j a v a2 s .  c o m*/
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
    if (prefs.getBoolean(Preferences.PREFS_KEY_LOG_ENABLE, Preferences.PREFS_DEFAULT_LOG_ENABLE)) {
        String head = new SimpleDateFormat("yyyyMMdd [hhmmssa]: \n", Locale.US).format(new Date());
        try {
            throw new Exception();
        } catch (Exception e) {
            StackTraceElement ste = e.getStackTrace()[1];
            String name = ste.getClassName();
            int n = -1;
            if ((n = name.lastIndexOf('.')) != -1)
                name = name.substring(n + 1);
            head += name + "->" + ste.getMethodName() + "(" + ste.getLineNumber() + ")\n";
        }
        ctx.getLogBuffer().add(head + msg);
    }
    ctx.unlock();
}

From source file:com.googlecode.flyway.commandline.Main.java

/**
 * Output class, method and line number infos of first stack trace element
 * of the given {@link Throwable} using {@link Log#error(Object)}.
 *
 * @param t {@link Throwable} to log//from   w ww  .  j  a  v  a2 s .co m
 */
private static void outputFirstStackTraceElement(Throwable t) {
    StackTraceElement firstStackTraceElement = t.getStackTrace()[0];
    LOG.error("Occured in " + firstStackTraceElement.getClassName() + "."
            + firstStackTraceElement.getMethodName() + "() at line " + firstStackTraceElement.getLineNumber());
}

From source file:com.asakusafw.testdriver.TestDriverTestToolsBase.java

private static Method findCaller() {
    StackTraceElement[] trace = new Throwable().getStackTrace();
    for (StackTraceElement element : trace) {
        try {//from   w  w  w .  j  a va 2s  .c om
            Class<?> aClass = Class.forName(element.getClassName());
            if (TestDriverTestToolsBase.class.isAssignableFrom(aClass)) {
                continue;
            }
            Method method = aClass.getDeclaredMethod(element.getMethodName());
            return method;
        } catch (Exception e) {
            continue;
        }
    }
    throw new IllegalStateException(
            "?????????????");
}

From source file:de.domjos.schooltools.helper.Helper.java

public static void printException(Context context, Throwable ex) {
    StringBuilder message = new StringBuilder(ex.getMessage() + "\n" + ex.toString());
    for (StackTraceElement element : ex.getStackTrace()) {
        message.append(element.getFileName()).append(":").append(element.getClassName()).append(":")
                .append(element.getMethodName()).append(":").append(element.getLineNumber());
    }// w w w .  j av  a  2s  .  co m
    Log.e("Exception", message.toString(), ex);
    Log4JHelper.getLogger(context.getPackageName()).error("Exception", ex);
    Helper.createToast(context, ex.getLocalizedMessage(), false);
}