List of usage examples for java.lang StackTraceElement getMethodName
public String getMethodName()
From source file:com.gargoylesoftware.htmlunit.WebTestCase.java
/** * Finds from the call stack the active running JUnit test case * @return the test case method//from w w w .j ava 2s.c o m * @throws RuntimeException if no method could be found */ private Method findRunningJUnitTestMethod() { final Class<?> cl = getClass(); final Class<?>[] args = new Class[] {}; // search the initial junit test final Throwable t = new Exception(); for (int i = t.getStackTrace().length - 1; i >= 0; i--) { final StackTraceElement element = t.getStackTrace()[i]; if (element.getClassName().equals(cl.getName())) { try { final Method m = cl.getMethod(element.getMethodName(), args); if (isPublicTestMethod(m)) { return m; } } catch (final Exception e) { // can't access, ignore it } } } throw new RuntimeException("No JUnit test case method found in call stack"); }
From source file:org.acmsl.commons.utils.ToStringUtils.java
/** * Checks whether given stack trace contains recursive calls to given class' method. * @param <T> the class type./*from www . j a v a2s. co m*/ * @param stackTrace the stack trace. * @param clazz the class. * @param methodName the method name. * @return {@code true} in such case. */ protected <T> boolean stackTraceContainsRecursiveCalls(@NotNull final StackTraceElement[] stackTrace, @NotNull final Class<T> clazz, @NotNull final String methodName) { boolean result = false; int count = 0; for (@Nullable final StackTraceElement stackEntry : stackTrace) { if (stackEntry != null) { @Nullable final String className = stackEntry.getClassName(); if ((className != null) && (className.equals(clazz.getName())) && (methodName.equals(stackEntry.getMethodName()))) { count++; } if (count == 2) { result = true; break; } } } return result; }
From source file:alma.acs.logging.AcsLogger.java
/** * Logs the given <code>LogRecord</code>. * The record can be modified or dropped by the optional filters provided in {@link #addLogRecordFilter(alma.acs.logging.AcsLogger.LogRecordFilter)}. * <p>/* www .j ava 2 s . com*/ * Adding of context information: * <ul> * <li> If the LogRecord has a parameter that is a map which contains additional information * about the line of code, thread, etc., the log record will be taken as provided, and no context * information will be added. This can be useful if * <ul> * <li> the log record was reconstructed from a remote error by the ACS error handling code * (see <code>AcsJException</code>), or * <li> if in very exceptional cases application code needs to manipulate such information by hand. * </ul> * <li> otherwise, context information is inferred, similar to {@link LogRecord#inferCaller()}, * but additionally including thread name and line of code. * </ul> * Note that by overloading this method, we intercept all logging activities of the base class. * * @see java.util.logging.Logger#log(java.util.logging.LogRecord) */ public void log(LogRecord record) { // Throw exception if level OFF was used to log this record, see http://jira.alma.cl/browse/COMP-1928 // Both Level.OFF and AcsLogLevel.OFF use the same value INTEGER.max, but we anyway check for both. if (record.getLevel().intValue() == Level.OFF.intValue() || record.getLevel().intValue() == AcsLogLevel.OFF.intValue()) { throw new IllegalArgumentException( "Level OFF must not be used for actual logging, but only for level filtering."); } StopWatch sw_all = null; if (PROFILE) { sw_all = new StopWatch(null); } // Level could be null and must then be inherited from the ancestor loggers, // e.g. during JDK shutdown when the log level is nulled by the JDK LogManager Logger loggerWithLevel = this; while (loggerWithLevel != null && loggerWithLevel.getLevel() == null && loggerWithLevel.getParent() != null) { loggerWithLevel = loggerWithLevel.getParent(); } int levelValue = -1; if (loggerWithLevel.getLevel() == null) { // HSO 2007-09-05: With ACS 6.0.4 the OMC uses this class (previously plain JDK logger) and has reported // that no level was found, which yielded a NPE. To be investigated further. // Probably #createUnconfiguredLogger was used without setting parent logger nor log level. // Just to be safe I add the necessary checks and warning message that improve over a NPE. if (!noLevelWarningPrinted) { System.out.println("Logger configuration error: no log level found for logger " + getLoggerName() + " or its ancestors. Will use Level.ALL instead."); noLevelWarningPrinted = true; } // @TODO: decide if resorting to ALL is desirable, or to use schema defaults, INFO, etc levelValue = Level.ALL.intValue(); } else { // level is fine, reset the flag to print the error message again when log level is missing. noLevelWarningPrinted = false; levelValue = loggerWithLevel.getLevel().intValue(); } // filter by log level to avoid unnecessary retrieval of context data. // The same check will be repeated by the base class implementation of this method that gets called afterwards. if (record.getLevel().intValue() < levelValue || levelValue == offValue) { return; } // modify the logger name if necessary if (loggerName != null) { record.setLoggerName(loggerName); } // check if this record already has the context data attached which ACS needs but the JDK logging API does not provide LogParameterUtil paramUtil = new LogParameterUtil(record); Map<String, Object> specialProperties = paramUtil.extractSpecialPropertiesMap(); if (specialProperties == null) { // we prepend the special properties map to the other parameters specialProperties = LogParameterUtil.createPropertiesMap(); List<Object> paramList = paramUtil.getNonSpecialPropertiesMapParameters(); paramList.add(0, specialProperties); record.setParameters(paramList.toArray()); String threadName = Thread.currentThread().getName(); specialProperties.put(LogParameterUtil.PARAM_THREAD_NAME, threadName); specialProperties.put(LogParameterUtil.PARAM_PROCESSNAME, this.processName); specialProperties.put(LogParameterUtil.PARAM_SOURCEOBJECT, this.sourceObject); // Get the stack trace StackTraceElement stack[] = (new Throwable()).getStackTrace(); // search for the first frame before the "Logger" class. int ix = 0; boolean foundNonLogFrame = false; while (ix < stack.length) { StackTraceElement frame = stack[ix]; String cname = frame.getClassName(); if (!foundNonLogFrame && !loggerClassNames.contains(cname)) { // We've found the relevant frame. record.setSourceClassName(cname); record.setSourceMethodName(frame.getMethodName()); int lineNumber = frame.getLineNumber(); specialProperties.put(LogParameterUtil.PARAM_LINE, Long.valueOf(lineNumber)); foundNonLogFrame = true; if (this.callStacksToBeIgnored.isEmpty()) { break; // performance optimization: avoid checking all "higher" stack frames } } if (foundNonLogFrame) { if (callStacksToBeIgnored.contains(concatenateIgnoreLogData(cname, frame.getMethodName()))) { //System.out.println("Won't log record with message " + record.getMessage()); return; } } ix++; } // We haven't found a suitable frame, so just punt. This is // OK as we are only committed to making a "best effort" here. } StopWatch sw_afterAcsLogger = null; if (PROFILE) { sw_afterAcsLogger = sw_all.createStopWatchForSubtask("afterAcsLogger"); LogParameterUtil logParamUtil = new LogParameterUtil(record); logParamUtil.setStopWatch(sw_afterAcsLogger); } // Let the delegate or Logger base class handle the rest. if (delegate != null) { delegate.log(record); } else { super.log(record); } if (PROFILE) { sw_afterAcsLogger.stop(); sw_all.stop(); long elapsedNanos = sw_all.getLapTimeNanos(); if (profileSlowestCallStopWatch == null || profileSlowestCallStopWatch.getLapTimeNanos() < elapsedNanos) { profileSlowestCallStopWatch = sw_all; } profileLogTimeStats.addValue(elapsedNanos); if (profileLogTimeStats.getN() >= profileStatSize) { String msg = "Local logging times in ms for the last " + profileStatSize + " logs: "; msg += "mean=" + profileMillisecFormatter.format(profileLogTimeStats.getMean() * 1E-6); msg += ", median=" + profileMillisecFormatter.format(profileLogTimeStats.getPercentile(50) * 1E-6); msg += ", stdev=" + profileMillisecFormatter.format(profileLogTimeStats.getStandardDeviation() * 1E-6); msg += "; details of slowest log (from "; msg += IsoDateFormat.formatDate(profileSlowestCallStopWatch.getStartTime()) + "): "; msg += profileSlowestCallStopWatch.getSubtaskDetails(); System.out.println(msg); profileSlowestCallStopWatch = null; profileLogTimeStats.clear(); } } }
From source file:be.agiv.security.demo.Main.java
private void showException(Exception e) { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(e.getMessage()); stringBuffer.append("\n"); for (StackTraceElement stackTraceElement : e.getStackTrace()) { stringBuffer.append(stackTraceElement.getClassName()); stringBuffer.append("."); stringBuffer.append(stackTraceElement.getMethodName()); stringBuffer.append(":"); stringBuffer.append(stackTraceElement.getLineNumber()); stringBuffer.append("\n"); }/*from w w w . j a v a 2s . c o m*/ Throwable cause = e.getCause(); while (null != cause) { stringBuffer.append("\n"); stringBuffer.append("Caused by: "); stringBuffer.append(cause.getMessage()); stringBuffer.append(" - "); stringBuffer.append(cause.getClass().getName()); stringBuffer.append("\n"); for (StackTraceElement stackTraceElement : e.getStackTrace()) { stringBuffer.append(stackTraceElement.getClassName()); stringBuffer.append("."); stringBuffer.append(stackTraceElement.getMethodName()); stringBuffer.append(":"); stringBuffer.append(stackTraceElement.getLineNumber()); stringBuffer.append("\n"); } cause = cause.getCause(); } JTextArea textArea = new JTextArea(stringBuffer.toString(), 10, 40); JScrollPane scrollPane = new JScrollPane(textArea); scrollPane.setAutoscrolls(true); JOptionPane.showMessageDialog(this, scrollPane, e.getClass().getSimpleName(), JOptionPane.ERROR_MESSAGE); }
From source file:org.schimpf.util.Logger.java
/** * Almacena el mensaje de una excepcion en el log * //from www. ja v a 2 s. c o m * @author <FONT style='color:#55A; font-size:12px; font-weight:bold;'>Hermann D. Schimpf</FONT> * @author <B>HDS Solutions</B> - <FONT style="font-style:italic;">Soluciónes Informáticas</FONT> * @version Oct 1, 2012 12:55:33 PM * @param level Nivel del mensaje * @param exception Excepcion a mostrar */ public synchronized void log(final Level level, final Throwable exception) { // verificamos si alguno esta habilitado if (!level.isEnabled(this.consoleLevel) && !level.isEnabled(this.fileLevel)) // salimos return; // generamos el inicio del mensaje final String logStart = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") .format(new Date(System.currentTimeMillis())) + " " + StringUtils.rightPad("[" + level.name() + "]", 9) + this.name + " "; // iniciamos el mensaje final StringBuffer log = new StringBuffer(logStart); // agregamos el mensaje de la excepcion log.append(exception.getClass().getName() + (exception.getMessage() != null ? ": " + exception.getMessage() : "")); // recorremos los pasos for (final StackTraceElement stackTrace : exception.getStackTrace()) // agregamos el elemento log.append("\n" + logStart + "\t" + stackTrace.getClassName() + "." + stackTrace.getMethodName() + "(" + stackTrace.getFileName() + ":" + stackTrace.getLineNumber() + ")"); // verificamos si mostramos en consola if (level.isEnabled(this.consoleLevel)) // verificamos si es >= ERROR if (level.isEnabled(Level.ERROR)) // mostrar el mensaje en consola de error System.err.println(log); else // mostrar el mensaje en consola de error System.out.println(log); // verificamos si mostramos en el fichero if (level.isEnabled(this.fileLevel) && this.logToFile) // escribimos la linea en el fichero this.writeToFile(log.toString()); // recorremos los listeners for (final LoggerListener listener : Logger.listeners) // enviamos el mensaje listener.log(this, log.toString(), level, true); }
From source file:smartrics.rest.fitnesse.fixture.RestFixture.java
private void debugMethodCall(String h) { if (debugMethodCall) { StackTraceElement el = Thread.currentThread().getStackTrace()[4]; LOG.debug(h + el.getMethodName()); }/*from w w w .j a va 2 s . co m*/ }
From source file:com.github.michalbednarski.intentslab.editor.IntentGeneralFragment.java
@Override public void onTrackerUpdate() { IntentTracker tracker = getIntentEditor().getIntentTracker(); FormattedTextBuilder ftb = new FormattedTextBuilder(); ftb.appendRaw("[Tracking intent]\naction " + (tracker.actionRead() ? "" : "NOT ") + "read"); ftb.appendText("Read extras:"); for (final ReadBundleEntryInfo entryInfo : tracker.getExtrasTracker().getReadEntries()) { ftb.appendClickable(entryInfo.name, new ClickableSpan() { @Override/*ww w . j a v a 2 s . co m*/ public void onClick(View widget) { String message = entryInfo.methodName; if (entryInfo.stackTrace != null) { message += "\n\n"; for (StackTraceElement element : entryInfo.stackTrace) { message += element.getClassName() + " " + element.getMethodName() + " " + element.getLineNumber() + "\n"; } } new AlertDialog.Builder(getActivity()).setTitle(entryInfo.name).setMessage(message).show(); } }); } mIntentTrackerSummary.setText(ftb.getText()); mIntentTrackerSummary.setVisibility(View.VISIBLE); }
From source file:com.dungnv.vfw5.base.dao.BaseFWDAOImpl.java
public String printLog(Exception e) { String str;//from w ww . j av a 2s . com try { e.printStackTrace(); str = " [DEATAIL]" + e.toString(); if (e.getCause() != null && e.getCause().getMessage() != null) { str += " - Caused by " + e.getCause().getMessage(); } StackTraceElement[] traceList = e.getStackTrace(); for (StackTraceElement trace : traceList) { if (trace.getClassName().contains("com.dungnv.framework.interceptor.ActionInterceptor") || trace .getClassName().contains("com.dungnv.config.tms.interceptor.LogActionInterceptor")) { break; } else if (trace.getClassName().contains("com.dungnv")) { str += "\n [" + trace.getClassName() + ".class][" + trace.getMethodName() + "][" + trace.getLineNumber() + "]"; } } } catch (Exception ex) { str = ":" + e.getMessage(); } return str; }
From source file:org.batoo.jpa.benchmark.BenchmarkTest.java
private void measureTime(long worked, ThreadInfo threadInfo) { TimeElement child = this.element; boolean gotStart = false; boolean last = false; boolean inDb = false; if (threadInfo == null) { return;/* w w w . j a va2 s . c o m*/ } for (int i = threadInfo.getStackTrace().length - 1; i >= 0; i--) { final StackTraceElement stElement = threadInfo.getStackTrace()[i]; if (this.isInDb(stElement)) { inDb = true; break; } } for (int i = threadInfo.getStackTrace().length - 1; i >= 0; i--) { final StackTraceElement stElement = threadInfo.getStackTrace()[i]; if (!gotStart && !stElement.getMethodName().startsWith("singleTest")) { continue; } gotStart = true; final String key = BenchmarkTest.SUMMARIZE ? // stElement.getClassName() + "." + stElement.getMethodName() : // stElement.getClassName() + "." + stElement.getMethodName() + "." + stElement.getLineNumber(); child = child.get(key); TimeElement child2 = this.elements.get(key); if (child2 == null) { this.elements.put(key, child2 = new TimeElement(key)); } if (this.isInDb(stElement) || (i == 0)) { child.addTime(worked, true, inDb); child2.addTime(worked, true, inDb); last = true; } else { child.addTime(worked, false, inDb); child2.addTime(worked, false, inDb); } if (last) { break; } } }
From source file:org.springframework.boot.SpringApplication.java
private Class<?> deduceMainApplicationClass() { try {// w w w . j av a 2 s.c om StackTraceElement[] stackTrace = new RuntimeException().getStackTrace(); for (StackTraceElement stackTraceElement : stackTrace) { if ("main".equals(stackTraceElement.getMethodName())) { return Class.forName(stackTraceElement.getClassName()); } } } catch (ClassNotFoundException ex) { // Swallow and continue } return null; }