Example usage for java.lang StackTraceElement getClassName

List of usage examples for java.lang StackTraceElement getClassName

Introduction

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

Prototype

public String getClassName() 

Source Link

Document

Returns the fully qualified name of the class containing the execution point represented by this stack trace element.

Usage

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>//from   ww w  .  jav a 2  s  .co  m
 * 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:op.tools.SYSTools.java

public static String getThrowableAsHTML(Throwable exc) {
    String html = "";
    StackTraceElement[] stacktrace = exc.getStackTrace();

    html += SYSConst.html_h1("mail.errormail.attachment.line1");
    html += SYSConst.html_h2(exc.getClass().getName());
    html += SYSConst.html_paragraph(exc.getMessage());

    if (OPDE.getMainframe().getCurrentResident() != null) {
        html += SYSConst.html_h3("ResID: " + OPDE.getMainframe().getCurrentResident().getRID());
    }/*from  w  w w . j a  va2  s. co  m*/

    html += SYSConst.html_h3(OPDE.getMainframe().getCurrentVisiblePanel().getInternalClassID());

    String table = SYSConst.html_table_th("mail.errormail.attachment.tab.col1")
            + SYSConst.html_table_th("mail.errormail.attachment.tab.col2")
            + SYSConst.html_table_th("mail.errormail.attachment.tab.col3")
            + SYSConst.html_table_th("mail.errormail.attachment.tab.col4");

    for (int exception = 0; exception < stacktrace.length; exception++) {
        StackTraceElement element = stacktrace[exception];
        table += SYSConst.html_table_tr(SYSConst.html_table_td(element.getMethodName())
                + SYSConst.html_table_td(Integer.toString(element.getLineNumber()))
                + SYSConst.html_table_td(element.getClassName())
                + SYSConst.html_table_td(element.getFileName()));
    }

    html += SYSConst.html_table(table, "1");

    // Possible Cause
    if (exc.getCause() != null) {
        html += SYSConst.html_h3("Caused by: " + exc.getCause().getMessage());
        StackTraceElement[] stacktrace1 = exc.getCause().getStackTrace();
        String table1 = SYSConst.html_table_th("mail.errormail.attachment.tab.col1")
                + SYSConst.html_table_th("mail.errormail.attachment.tab.col2")
                + SYSConst.html_table_th("mail.errormail.attachment.tab.col3")
                + SYSConst.html_table_th("mail.errormail.attachment.tab.col4");

        for (int exception = 0; exception < stacktrace1.length; exception++) {
            StackTraceElement element = stacktrace1[exception];
            table1 += SYSConst.html_table_tr(SYSConst.html_table_td(element.getMethodName())
                    + SYSConst.html_table_td(Integer.toString(element.getLineNumber()))
                    + SYSConst.html_table_td(element.getClassName())
                    + SYSConst.html_table_td(element.getFileName()));
        }

        html += SYSConst.html_table(table1, "1");
    }

    return html;
}

From source file:org.sakaiproject.status.StatusServlet.java

protected void reportThreadStackTraces(HttpServletResponse response) throws Exception {
    PrintWriter pw = response.getWriter();

    for (Thread thread : findAllThreads()) {
        if (thread != null) {
            String stackTrace = "";
            try {
                StackTraceElement[] stack = thread.getStackTrace();
                for (StackTraceElement ste : stack) {
                    stackTrace += ste.getClassName() + "." + ste.getMethodName() + "();" + ste.getFileName()
                            + ":" + ste.getLineNumber() + " ";
                }//ww  w.  j a v a2s .c o  m
            } catch (Exception e) {
                stackTrace += "-";
            }
            pw.print(thread.getThreadGroup().getName() + " " + thread.getId() + " " + stackTrace + "\n");
        }
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.util.ExceptionInformation.java

private final StackTraceElement getStackTraceElementForActionMapping(HttpServletRequest request,
        ActionMapping mapping, StackTraceElement[] elements) {
    Class<?> actionClass = actionClass(mapping.getType());
    setActionErrorClass(actionClass);/*from  w  w  w.  j  a va2 s  .co  m*/
    String methodName = DispatchAction.class.isAssignableFrom(actionClass)
            ? request.getParameter(mapping.getParameter())
            : "execute";
    setActionErrorMethod(methodName);
    for (StackTraceElement element : elements) {
        if (element.getClassName().equals(mapping.getType()) && element.getMethodName().equals(methodName)) {
            return element;
        }
    }
    return null;
}

From source file:com.dungnv.vfw5.base.dao.BaseFWDAOImpl.java

public String printLog(Exception e) {
    String str;// ww  w .  j a  va 2s  .c om
    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:com.rvantwisk.cnctools.controllers.CNCToolsController.java

/**
 * Handle exception and show a strack trace, at least to inform the user that something was wrong
 * This is also a last resort, if you can handle the exception in the dialog, please do so and instruct the user!
 *
 * @param exception/*ww w  . j ava 2s  . c o  m*/
 */
public void handleException(Exception exception) {
    logger.error("generateGCode: General Exception", exception);
    final FXMLDialog dialog = screens.errorDialog();
    ErrorController controller = dialog.getController();
    StringBuilder sb = new StringBuilder();

    sb.append(exception.toString()).append("\n");
    for (StackTraceElement trace : exception.getStackTrace()) {
        if (trace.getClassName().startsWith("com.rvantwisk")) {
            sb.append(trace.getClassName()).append(":").append(trace.getMethodName()).append(":")
                    .append(trace.getLineNumber()).append("\n");
        }
    }
    controller.setMessage(sb.toString());
    dialog.showAndWait();
}

From source file:org.batoo.jpa.benchmark.BenchmarkTest.java

private boolean isInDb(final StackTraceElement stElement) {
    return stElement.getClassName().startsWith("org.apache.derby")
            || stElement.getClassName().startsWith("com.mysql") || stElement.getClassName().startsWith("org.h2")
            || stElement.getClassName().startsWith("org.hsqldb");
}

From source file:com.clustercontrol.commons.util.JpaTransactionManager.java

/**
 * ?/*from   ww  w .  j a v a2 s .  c o m*/
 */
public void close() {
    if (!nestedEm && em != null) {
        if (em.isOpen()) {
            try {
                List<JpaTransactionCallback> callbacks = getCallbacks();

                if (!isCallbacked()) {
                    for (JpaTransactionCallback callback : callbacks) {
                        if (m_log.isDebugEnabled()) {
                            m_log.debug("executing callback preClose : " + callback.getClass().getName());
                        }
                        try {
                            setCallbacked();

                            callback.preClose();
                        } catch (Throwable t) {
                            m_log.warn("callback execution failure : " + callback.getClass().getName(), t);
                        } finally {
                            unsetCallbacked();
                        }
                    }
                }

                // commit or rollback???close?????????(rollback)?
                // ???connection????????
                EntityTransaction tx = em.getTransaction();
                if (tx.isActive()) {
                    if (m_log.isDebugEnabled()) {
                        StackTraceElement[] eList = Thread.currentThread().getStackTrace();
                        StringBuilder trace = new StringBuilder();
                        for (StackTraceElement e : eList) {
                            if (trace.length() > 0) {
                                trace.append("\n");
                            }
                            trace.append(String.format("%s.%s(%s:%d)", e.getClassName(), e.getMethodName(),
                                    e.getFileName(), e.getLineNumber()));
                        }
                        m_log.debug(
                                "closing uncompleted transaction. this transaction will be rollbacked before closing : "
                                        + trace);
                    }
                    tx.rollback();
                }

                em.close();
                HinemosSessionContext.instance().setProperty(JpaTransactionManager.EM, null);

                // postClose???innerTransaction????????callback???
                for (JpaTransactionCallback callback : callbacks) {
                    if (m_log.isDebugEnabled()) {
                        m_log.debug("executing callback postClose : " + callback.getClass().getName());
                    }
                    try {
                        callback.postClose();
                    } catch (Throwable t) {
                        m_log.warn("callback execution failure : " + callback.getClass().getName(), t);
                    }
                }
            } finally {
                HinemosSessionContext.instance().setProperty(JpaTransactionManager.EM, null);
            }
        }
        HinemosSessionContext.instance().setProperty(EM, null);
    }
}

From source file:io.teak.sdk.Raven.java

public void reportException(Throwable t) {
    if (t == null) {
        return;/*from   w  w  w  .  j a  va 2s  . c o  m*/
    }

    HashMap<String, Object> additions = new HashMap<>();
    ArrayList<Object> exceptions = new ArrayList<>();
    HashMap<String, Object> exception = new HashMap<>();

    exception.put("type", t.getClass().getSimpleName());
    exception.put("value", t.getMessage());
    exception.put("module", t.getClass().getPackage().getName());

    HashMap<String, Object> stacktrace = new HashMap<>();
    ArrayList<Object> stackFrames = new ArrayList<>();

    StackTraceElement[] steArray = t.getStackTrace();
    for (int i = steArray.length - 1; i >= 0; i--) {
        StackTraceElement ste = steArray[i];
        HashMap<String, Object> frame = new HashMap<>();

        frame.put("filename", ste.getFileName());

        String method = ste.getMethodName();
        if (method.length() != 0) {
            frame.put("function", method);
        }

        int lineno = ste.getLineNumber();
        if (!ste.isNativeMethod() && lineno >= 0) {
            frame.put("lineno", lineno);
        }

        String module = ste.getClassName();
        frame.put("module", module);

        boolean in_app = true;
        if (module.startsWith("android.") || module.startsWith("java.") || module.startsWith("dalvik.")
                || module.startsWith("com.android.")) {
            in_app = false;
        }

        frame.put("in_app", in_app);

        stackFrames.add(frame);
    }
    stacktrace.put("frames", stackFrames);

    exception.put("stacktrace", stacktrace);

    exceptions.add(exception);
    additions.put("exception", exceptions);

    try {
        Report report = new Report(t.getMessage(), Level.ERROR, additions);
        report.sendToService();
    } catch (Exception e) {
        Log.e(LOG_TAG, "Unable to report Teak SDK exception. " + Log.getStackTraceString(t) + "\n"
                + Log.getStackTraceString(e));
    }
}

From source file:com.mirth.connect.donkey.test.util.TestUtils.java

private static String getCallingMethod() {
    StackTraceElement[] trace = Thread.currentThread().getStackTrace();
    StackTraceElement element = trace[3];
    return String.format("%s.%s:%d", element.getClassName(), element.getMethodName(), element.getLineNumber());
}