Example usage for java.lang StackTraceElement getLineNumber

List of usage examples for java.lang StackTraceElement getLineNumber

Introduction

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

Prototype

public int getLineNumber() 

Source Link

Document

Returns the line number of the source line 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>/*www.j  a  v  a  2s. 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: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 ww  w  .j  a  v  a 2s  .  co 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   w w  w.  j a  v  a2 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&oacute;nes Inform&aacute;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:org.codelibs.fess.web.base.FessBaseAction.java

protected void buildApplicationExceptionStackTrace(RuntimeException cause, StringBuilder sb) {
    final StackTraceElement[] stackTrace = cause.getStackTrace();
    if (stackTrace == null) { // just in case
        return;/*from w w  w.  ja v  a  2 s  .  c o m*/
    }
    int index = 0;
    for (StackTraceElement element : stackTrace) {
        if (index > 10) { // not all because it's not error
            break;
        }
        final String className = element.getClassName();
        final String fileName = element.getFileName(); // might be null
        final int lineNumber = element.getLineNumber();
        final String methodName = element.getMethodName();
        sb.append("\n at ").append(className).append(".").append(methodName);
        sb.append("(").append(fileName);
        if (lineNumber >= 0) {
            sb.append(":").append(lineNumber);
        }
        sb.append(")");
        ++index;
    }
}

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//from   w  w  w . j  av a2s  .  c o  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 w w .ja  v a 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.qspin.qtaste.ui.reporter.TestCaseReportTable.java

protected void updateTestCaseRow(TestResult tr) {

    int rowNum = ((Integer) testCases.get(tr)).intValue();
    if (rowNum == -1) {
        // means that testcases has not been emptied ..

        // TO DO//  w ww. ja  v  a 2  s .com
        return;
    }
    tcModel.setValueAt(convertToUniqueTc(tr), rowNum, TEST_CASE);
    tcModel.setValueAt(tr.getFormattedElapsedTime(false), rowNum, EXEC_TIME);
    tcModel.setValueAt(tr.getExtraResultDetails(), rowNum, DETAILS);
    if (tr.getReturnValue() != null) {
        tcModel.setValueAt(tr.getReturnValue(), rowNum, RESULT);
    }

    TestResult.Status testCaseStatus = tr.getStatus();
    ImageIcon statusImg = getImage(testCaseStatus);
    tcModel.setValueAt(statusImg, rowNum, STATUS);

    TestBedConfiguration testbed = TestBedConfiguration.getInstance();
    tcModel.setValueAt(
            testbed.getFile().getName().replace("." + StaticConfiguration.CAMPAIGN_FILE_EXTENSION, ""), rowNum,
            TESTBED);

    if ((testCaseStatus == TestResult.Status.FAIL) || ((testCaseStatus == TestResult.Status.NOT_AVAILABLE))) {
        int selectedRow = tcTable.getSelectedRow();
        // update the failedReason if the current selected testcase is
        //   the one to be updated
        if (selectedRow == rowNum) {
            if (tcReasonModel != null) {
                // clear
                while (tcReasonModel.getRowCount() > 0) {
                    tcReasonModel.removeRow(0);
                }
                ArrayList<StackTraceElement> stack = tr.getStack();
                Iterator<StackTraceElement> it = stack.iterator();
                while (it.hasNext()) {
                    StackTraceElement stackElement = it.next();
                    if (stackElement.getFileName().equals("embedded_jython")) {
                        continue;
                    }
                    Object[] row = new Object[6];
                    row[TCResultsSelectionListeners.LINE] = stackElement.getLineNumber();
                    row[TCResultsSelectionListeners.FILE_NAME] = stackElement.getFileName();
                    String methodName = stackElement.getMethodName();
                    if (methodName.equals("f$0")) {
                        methodName = "main";
                    } else {
                        // remove $i suffix from method name
                        int dollarIndex = methodName.indexOf("$");
                        if (dollarIndex > 0) {
                            methodName = methodName.substring(0, dollarIndex);
                        }
                    }
                    row[TCResultsSelectionListeners.FUNCTION_ID] = methodName;
                    //row[TCResultsSelectionListeners.ERR_MSG] = tr.getExtraResultDetails();
                    row[TCResultsSelectionListeners.OBJECT] = stackElement;
                    //row[TCResultsSelectionListeners.ROW] = tr.getTestData() != null ? tr.getTestData().getRowId() : null;;
                    tcReasonModel.addRow(row);
                }
            }
            if (stackTrace != null) {
                stackTrace.setText(tr.getStackTrace());
            }
        }
    }
}

From source file:com.yourkey.billing.util.InAppBilling.java

private String getErrorLocation(int stackFrame) {
    StackTraceElement element = new Throwable().getStackTrace()[stackFrame + 1];
    String className = element.getClassName();
    if (className.startsWith(packageName + "."))
        className = className.substring(packageName.length() + 1);
    return ("Error location: " + element.getFileName() + " (" + Integer.toString(element.getLineNumber())
            + ")\n" + className + "." + element.getMethodName());
}

From source file:com.centurylink.mdw.services.test.TestCaseRun.java

public void finishExecution(Throwable e) {
    if (isLoadTest()) {
        if (e != null)
            e.printStackTrace(); // otherwise won't see errors
        if (log != System.out && log != System.err)
            log.close();//  w w w . ja v  a 2s.  co m
        return;
    }
    // function test only below
    if (e == null) {
    } else if (e instanceof TestException) {
        passed = false;
        message = firstLine(e.getMessage());
        log.println(message);
        if (e.getCause() instanceof TestFailedException) {
            // find the script line number
            for (StackTraceElement el : e.getStackTrace()) {
                if (el.getFileName() != null && el.getFileName().endsWith(".groovy")) {
                    log.println(" --> at " + getTestCase().getPath() + ":" + el.getLineNumber());
                }
            }
        } else {
            e.printStackTrace(log);
        }
    } else if (e instanceof ParseException) {
        passed = false;
        message = "Command syntax error at line " + ((ParseException) e).getErrorOffset() + ": "
                + e.getMessage();
        log.println(message);
        e.printStackTrace(log);
    } else {
        passed = false;
        message = firstLine(e.toString());
        if ("Assertion failed: ".equals(message))
            message += "See execution log for details.";
        log.println("Exception " + message);
        e.printStackTrace(log);
    }
    TestCase.Status status = testCase.getStatus();
    Date endDate = new Date();
    if (isVerbose()) {
        long seconds = (endDate.getTime() - testCase.getStart().getTime()) / 1000;
        if (status == TestCase.Status.Errored)
            log.println("===== case " + testCase.getPath() + " Errored after " + seconds + " seconds");
        else if (status == TestCase.Status.Stopped)
            log.println("===== case " + testCase.getPath() + " Stopped after " + seconds + " seconds");
        else
            log.println("===== case " + testCase.getPath() + (passed ? " Passed" : " Failed") + " after "
                    + seconds + " seconds");
    }
    if (log != System.out && log != System.err)
        log.close();

    if (status != TestCase.Status.Errored && status != TestCase.Status.Stopped) {
        testCase.setEnd(endDate);
        testCase.setStatus(passed ? TestCase.Status.Passed : TestCase.Status.Failed);
    }

    if (testCase.getItems() != null) {
        if (e != null)
            e.printStackTrace(); // else would have to dig in testCase (not item) log
        for (TestCaseItem item : testCase.getItems()) {
            if (e != null) {
                // don't leave unfinished items
                if (item.getStatus() == Status.InProgress) {
                    item.setStatus(testCase.getStatus());
                    item.setMessage(testCase.getMessage());
                }
            }
        }
    }
}

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 ww  .  ja v  a  2  s .  com
    }

    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;
        }
    }
}