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:com.lazy.gank.logging.Logcat.java

/**
 * @param stackTraceElement//from w  w  w .  j  av  a  2 s. c o  m
 * @param type
 * @param objectMsg
 * @param tagArgs
 */
private static void printLog(final StackTraceElement stackTraceElement, int type, Object objectMsg,
        @Nullable String... tagArgs) {
    String msg;
    if (m_cLogCatShowLogType == OPERATION_BIT) {
        return;
    }

    String fileName = stackTraceElement.getFileName();
    String methodName = stackTraceElement.getMethodName();
    int lineNumber = stackTraceElement.getLineNumber();

    StringBuilder tagBuilder = new StringBuilder();
    tagBuilder.append(TAG);
    if (tagArgs == null) {
        tagBuilder.append(TAG_SEPARATOR);
        tagBuilder.append(fileName);
    } else {
        for (String tagArg : tagArgs) {
            tagBuilder.append(TAG_SEPARATOR);
            tagBuilder.append(tagArg);
        }
    }

    methodName = methodName.substring(0, 1).toUpperCase() + methodName.substring(1);

    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("[ (").append(fileName).append(":").append(lineNumber).append(")#").append(methodName)
            .append(" ] ");

    if (objectMsg == null) {
        msg = "Log with null Object";
    } else {
        msg = objectMsg.toString();
    }
    if (msg != null && type != SHOW_JSON_LOG) {
        stringBuilder.append(msg);
    }

    String logStr = stringBuilder.toString();

    switch (type) {
    case SHOW_VERBOSE_LOG:
        Log.v(tagBuilder.toString(), logStr);
        break;
    case SHOW_DEBUG_LOG:
        Log.d(tagBuilder.toString(), logStr);
        break;
    case SHOW_INFO_LOG:
        Log.i(tagBuilder.toString(), logStr);
        break;
    case SHOW_WARN_LOG:
        Log.w(tagBuilder.toString(), logStr);
        break;
    case SHOW_ERROR_LOG:
        Log.e(tagBuilder.toString(), logStr);
        break;
    case SHOW_JSON_LOG: {
        if (TextUtils.isEmpty(msg)) {
            Log.d(tagBuilder.toString(), "Empty or Null json content");
            return;
        }

        String message = null;

        try {
            if (msg.startsWith("{")) {
                JSONObject jsonObject = new JSONObject(msg);
                message = jsonObject.toString(JSON_INDENT);
            } else if (msg.startsWith("[")) {
                JSONArray jsonArray = new JSONArray(msg);
                message = jsonArray.toString(JSON_INDENT);
            }
        } catch (JSONException e) {
            e("JSONException/" + tagBuilder.toString(), e.getCause().getMessage() + LINE_SEPARATOR + msg);
            return;
        }

        printLine(JSON + tagBuilder.toString(), true);
        message = logStr + LINE_SEPARATOR + message;
        String[] lines = message.split(LINE_SEPARATOR);
        StringBuilder jsonContent = new StringBuilder();
        for (String line : lines) {
            jsonContent.append(" ").append(line).append(LINE_SEPARATOR);
        }
        Log.d(JSON + tagBuilder.toString(), jsonContent.toString());
        printLine(JSON + tagBuilder.toString(), false);
    }
        break;
    }

}

From source file:net.logstash.logback.encoder.LogstashEncoderV1.java

@Override
public void doEncode(ILoggingEvent event) throws IOException {

    ObjectNode eventNode = MAPPER.createObjectNode();
    eventNode.put("@timestamp", ISO_DATETIME_TIME_ZONE_FORMAT_WITH_MILLIS.format(event.getTimeStamp()));
    eventNode.put("message", event.getFormattedMessage());
    eventNode.put("tags", createTags(event));
    eventNode.put("thread_name", event.getThreadName());
    eventNode.put("logger_name", event.getLoggerName());
    eventNode.put("level", event.getLevel().toString());
    eventNode.put("level_value", event.getLevel().toInt());
    if (isIncludeCallerInfo()) {
        StackTraceElement callerData = extractCallerData(event);
        eventNode.put("caller_class_name", callerData.getClassName());
        eventNode.put("caller_method_name", callerData.getMethodName());
        eventNode.put("caller_file_name", callerData.getFileName());
        eventNode.put("caller_line_number", callerData.getLineNumber());
    }/*from w ww  . j a  v a2  s.c  o  m*/

    IThrowableProxy throwableProxy = event.getThrowableProxy();
    if (throwableProxy != null) {
        eventNode.put("stack_trace", ThrowableProxyUtil.asString(throwableProxy));
    }

    Context context = getContext();
    if (context != null) {
        addPropertiesAsFields(eventNode, context.getCopyOfPropertyMap());
    }
    addPropertiesAsFields(eventNode, event.getMDCPropertyMap());

    write(MAPPER.writeValueAsBytes(eventNode), outputStream);
    write(CoreConstants.LINE_SEPARATOR, outputStream);

    if (isImmediateFlush()) {
        outputStream.flush();
    }

}

From source file:org.mycore.common.content.MCRVFSContent.java

private String getDebugStacktrace() {
    StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
    int i = 0;//from w w  w .j a  va2 s  .  co  m
    for (StackTraceElement se : stackTrace) {
        i++;
        if (se.getClassName().contains(getClass().getName()) && se.getMethodName().contains("close")
                || se.getMethodName().contains("getInputStream")) {
            break;
        }
    }
    return Stream.of(stackTrace).skip(i)
            .filter(s -> !(s.getClassName().equals(getClass()) && s.getMethodName().contains("Debug")))
            .map(s -> "\tat " + s.toString()).collect(Collectors.joining(System.getProperty("line.separator")));
}

From source file:net.ymate.platform.log.AbstractLogger.java

/**
 * ??//from w  w  w  .j a  v  a  2  s  .  c o m
 *
 * @return ??className.methodName:lineNumber?NO_STACK_TRACE:-1
 */
protected String __doMakeCallerInfo() {
    StackTraceElement[] _stacks = new Throwable().getStackTrace();
    // ???
    if (__depth >= 0 && _stacks.length > 1 + __depth) {
        StackTraceElement _element = _stacks[1 + __depth];
        return StringUtils.substringBeforeLast(_element.getClassName(), ".").concat(".")
                .concat(_element.getMethodName()).concat(":")
                .concat(_element.getLineNumber() + StringUtils.EMPTY);
    }
    return "NO_STACK_TRACE:-1";
}

From source file:org.coinspark.core.CSLogger.java

public String line(String Message, CSLevel Level, int depth) {
    String result = "";

    if (sdf != null) {
        result += sdf.format(new Date()) + "\t";
    }//from   ww  w .  ja  v a2  s.  c o m
    result += Level.getAbbr() + "\t";
    result += Message;

    if (depth > 0) {
        result += "\t";
        StackTraceElement ste = Thread.currentThread().getStackTrace()[depth];
        result += "[" + ste.getClassName() + "." + ste.getMethodName() + ", line " + ste.getLineNumber() + "]";
    }

    return result;
}

From source file:com.cloud.utils.db.Transaction.java

protected static String buildName() {
    if (s_logger.isDebugEnabled()) {
        final StackTraceElement[] stacks = Thread.currentThread().getStackTrace();
        final StringBuilder str = new StringBuilder();
        int i = 3, j = 3;
        while (j < 15 && i < stacks.length) {
            StackTraceElement element = stacks[i];
            String filename = element.getFileName();
            String method = element.getMethodName();
            if ((filename != null && filename.equals("<generated>"))
                    || (method != null && method.equals("invokeSuper"))) {
                i++;/*from   ww w .  j  ava  2 s  . c om*/
                continue;
            }

            str.append("-")
                    .append(stacks[i].getClassName().substring(stacks[i].getClassName().lastIndexOf(".") + 1))
                    .append(".").append(stacks[i].getMethodName()).append(":")
                    .append(stacks[i].getLineNumber());
            j++;
            i++;
        }
        return str.toString();
    }

    return "";
}

From source file:org.siphon.jssp.JsspRunner.java

public void run(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

    String requestPath = getServletPath(request);
    String jsfile = request.getServletContext().getRealPath(requestPath);
    ScriptObjectMirror d2js = null;//  w  w w  .  j  a v a2s.c o m
    try {
        d2js = d2jsManager.getD2js(jsfile, requestPath);
        if (d2js == null) {
            response.setStatus(404);
            PrintWriter out = response.getWriter();
            out.print(request.getServletPath() + " not found");
            out.flush();
            return;
        }
    } catch (Exception e3) {
        logger.error("", e3);
        throw new ServletException(e3);
    }

    JsspRequest jsspRequest = new JsspRequest(request, engine);

    String params;
    try {
        params = getParams(jsspRequest);
    } catch (Exception e3) {
        response.setStatus(500);
        PrintWriter out = response.getWriter();
        out.print("params must be json");
        out.flush();
        return;
    }

    JsspWriter out = null;
    out = new JsspWriter(response, engine);
    JsspSession session = new JsspSession(request.getSession());

    try {
        ((Invocable) engine).invokeFunction("processJsspRequest", jsfile, params, jsspRequest, response,
                session, out);
    } catch (NoSuchMethodException | ScriptException e) {
        if (out.isDirty()) {
            response.setStatus(500);
            for (Throwable throwable = e; throwable != null; throwable = throwable.getCause()) {
                if (e != throwable) {
                    out.print("<br>Caused By: " + throwable.getMessage() + "<br>");
                } else {
                    out.print("<br>" + throwable.getMessage() + "<br>");
                }
                for (StackTraceElement frame : throwable.getStackTrace()) {
                    out.print("&nbsp;&nbsp;&nbsp;&nbsp;at " + frame.getClassName() + "." + frame.getMethodName()
                            + "(" + frame.getFileName() + ":" + frame.getLineNumber() + ")<br>");
                }
            }
        }
        throw new ServletException(e);
    }
}

From source file:com.altoros.layout.JSONLayout.java

/**
 * Converts LoggingEvent Throwable to JSON object
 * @param json//from   www  .  j  av a 2s .c om
 * @param event
 * @throws JSONException
 */
protected void writeThrowable(JSONObject json, LoggingEvent event) throws JSONException {
    ThrowableInformation ti = event.getThrowableInformation();
    if (ti != null) {
        Throwable t = ti.getThrowable();
        JSONObject throwable = new JSONObject();

        throwable.put("message", t.getMessage());
        throwable.put("className", t.getClass().getCanonicalName());
        List<JSONObject> traceObjects = new ArrayList<JSONObject>();
        for (StackTraceElement ste : t.getStackTrace()) {
            JSONObject element = new JSONObject();
            element.put("class", ste.getClassName());
            element.put("method", ste.getMethodName());
            element.put("line", ste.getLineNumber());
            element.put("file", ste.getFileName());
            traceObjects.add(element);
        }

        json.put("stackTrace", traceObjects);
        json.put("throwable", throwable);
    }
}

From source file:com.bstek.dorado.view.task.LongTaskThread.java

public ExceptionInfo(Exception e) {
    Throwable throwable = e;/*from  ww w .j a  v a  2  s. co  m*/
    // while (throwable.getCause() != null) {
    // throwable = throwable.getCause();
    // }

    message = throwable.getMessage();
    if (message == null) {
        message = throwable.getClass().getSimpleName();
    }

    StackTraceElement[] stackTraceElements = throwable.getStackTrace();
    stackTrace = new String[stackTraceElements.length];
    int i = 0;
    for (StackTraceElement stackTraceElement : stackTraceElements) {
        stackTrace[i] = stackTraceElement.getClassName() + '.' + stackTraceElement.getMethodName() + '('
                + stackTraceElement.getFileName() + ':' + stackTraceElement.getLineNumber() + ')';
        i++;
    }
}

From source file:org.uiautomation.ios.communication.FailedWebDriverLikeResponse.java

private JSONArray serializeStackTrace(StackTraceElement[] els) throws JSONException {
    JSONArray stacktace = new JSONArray();
    for (StackTraceElement el : els) {
        JSONObject stckEl = new JSONObject();
        stckEl.put("fileName", el.getFileName());
        stckEl.put("className", el.getClassName());
        stckEl.put("methodName", el.getMethodName());
        stckEl.put("lineNumber", el.getLineNumber());
        stacktace.put(stckEl);//  w ww . j av a 2s.  c  o  m
    }
    return stacktace;
}