Java Code Examples for ch.qos.logback.classic.spi.ILoggingEvent#getCallerData()

The following examples show how to use ch.qos.logback.classic.spi.ILoggingEvent#getCallerData() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DingTalkAppender.java    From jframework with Apache License 2.0 6 votes vote down vote up
private String transformStackTrace(ILoggingEvent event) {
    String exception = "";
    IThrowableProxy throwableProxy =  event.getThrowableProxy();
    if (throwableProxy != null) {
        exception = ThrowableProxyUtil.asString(throwableProxy);
    }

    StackTraceElement[] callerData = event.getCallerData();
    StackTraceElement stackTraceElement = callerData[0];

    String time = DEFAULT_DATE_FORMAT.format(new Date(event.getTimeStamp()));
    String threadName = event.getThreadName();
    String level = event.getLevel().toString();
    String logger = event.getLoggerName();
    String msg = event.getFormattedMessage();
    String className = stackTraceElement.getClassName();
    String method = stackTraceElement.getMethodName();
    int lineNumber = stackTraceElement.getLineNumber();

    return String.format(FORMAT_MESSAGE, time, threadName, level, logger, className, method, lineNumber, exception, msg);
}
 
Example 2
Source File: CustomJsonLayout.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@Override
protected void addCustomDataToJsonMap(Map<String, Object> map, ILoggingEvent event) {
    add(HOST, includeHost, HOST_NAME, map);
    if (event.hasCallerData()) {
        StackTraceElement callerData = event.getCallerData()[0];
        addLine(LINE_NUMBER, includeLineNumber, callerData.getLineNumber(), map);
        add(CLASS_NAME, includeClassName, callerData.getClassName(), map);
        add(METHOD_NAME, includeMethodName, callerData.getMethodName(), map);
        add(FILE_NAME, includeFileName, callerData.getFileName(), map);
    }
    if (additionalFields != null) {
        additionalFields.forEach(field -> {
            String[] p = field.split("\\|");
            if (p.length == 2) {
                add(p[0], true, p[1], map);
            } else {
                addWarn("Unable to parse property string: " + field);
            }
        });
    }
}
 
Example 3
Source File: MongoDBAppender.java    From heimdall with Apache License 2.0 6 votes vote down vote up
@Override
protected void append(ILoggingEvent e) {
       ZoneId zoneId = ZoneId.of(this.zoneId);

       // Offset in milliseconds based on the informed Zone
       long offset = zoneId.getRules().getOffset(Instant.now()).getTotalSeconds() * 1000;

	Map<String, Object> objLog = new HashMap<>();
	objLog.put("ts", new BsonDateTime(e.getTimeStamp() + offset));
	objLog.put("trace", BasicDBObject.parse(e.getFormattedMessage()));
	objLog.put("level", e.getLevel().toString());
	objLog.put("logger", e.getLoggerName());
	objLog.put("thread", e.getThreadName());

	if (e.hasCallerData()) {
		StackTraceElement st = e.getCallerData()[0];
		String callerData = String.format("%s.%s:%d", st.getClassName(), st.getMethodName(), st.getLineNumber());
		objLog.put("caller", callerData);
	}
	Map<String, String> mdc = e.getMDCPropertyMap();
	if (mdc != null && !mdc.isEmpty()) {
		objLog.put("mdc", new BasicDBObject(mdc));
	}
	collection.insertOne(new Document(objLog));
}
 
Example 4
Source File: CustomJsonLayout.java    From kafka-logback with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected void addCustomDataToJsonMap(Map<String, Object> map, ILoggingEvent event) {
    add(HOST, includeHost, HOST_NAME, map);
    if (event.hasCallerData()) {
        StackTraceElement callerData = event.getCallerData()[0];
        addLine(LINE_NUMBER, includeLineNumber, callerData.getLineNumber(), map);
        add(CLASS_NAME, includeClassName, callerData.getClassName(), map);
        add(METHOD_NAME, includeMethodName, callerData.getMethodName(), map);
        add(FILE_NAME, includeFileName, callerData.getFileName(), map);
    }

    if (additionalFields != null) {
        additionalFields.forEach(field -> {
            String[] p = field.split("\\|");
            if (p.length == 2) {
                add(p[0], true, p[1], map);
            } else {
                addWarn("Unable to parse property string: " + field);
            }
        });
    }
}
 
Example 5
Source File: JsonFormatter.java    From log_to_kafka with MIT License 6 votes vote down vote up
public String format(ILoggingEvent event) {
  JSONObject jsonObject = new JSONObject();
  jsonObject.put("level", event.getLevel().levelStr);
  jsonObject.put("class", event.getLoggerName());
  jsonObject.put("timestamp", new DateTime(event.getTimeStamp()).toString("yyyy-MM-dd HH:mm:ss"));
  jsonObject.put("message", event.getFormattedMessage());

  if (includeMethodAndLineNumber) {
    StackTraceElement[] callerDataArray = event.getCallerData();
    if (callerDataArray != null && callerDataArray.length > 0) {
      StackTraceElement stackTraceElement = callerDataArray[0];
      jsonObject.put("method", stackTraceElement.getMethodName());
      jsonObject.put("line", stackTraceElement.getLineNumber() + "");
    }
  }
  if (this.extraPropertiesMap != null) {
    jsonObject.putAll(extraPropertiesMap);
  }
  return jsonObject.toJSONString();
}
 
Example 6
Source File: EcsEncoder.java    From ecs-logging-java with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] encode(ILoggingEvent event) {
    StringBuilder builder = new StringBuilder();
    EcsJsonSerializer.serializeObjectStart(builder, event.getTimeStamp());
    EcsJsonSerializer.serializeLogLevel(builder, event.getLevel().toString());
    EcsJsonSerializer.serializeFormattedMessage(builder, event.getFormattedMessage());
    serializeMarkers(event, builder);
    EcsJsonSerializer.serializeServiceName(builder, serviceName);
    EcsJsonSerializer.serializeEventDataset(builder, eventDataset);
    EcsJsonSerializer.serializeThreadName(builder, event.getThreadName());
    EcsJsonSerializer.serializeLoggerName(builder, event.getLoggerName());
    serializeAdditionalFields(builder);
    EcsJsonSerializer.serializeMDC(builder, event.getMDCPropertyMap());
    if (includeOrigin) {
        StackTraceElement[] callerData = event.getCallerData();
        if (callerData != null && callerData.length > 0) {
            EcsJsonSerializer.serializeOrigin(builder, callerData[0]);
        }
    }
    IThrowableProxy throwableProxy = event.getThrowableProxy();
    if (throwableProxy instanceof ThrowableProxy) {
        EcsJsonSerializer.serializeException(builder, ((ThrowableProxy) throwableProxy).getThrowable(), stackTraceAsArray);
    } else if (throwableProxy != null) {
        EcsJsonSerializer.serializeException(builder, throwableProxy.getClassName(), throwableProxy.getMessage(), throwableProxyConverter.convert(event), stackTraceAsArray);
    }
    EcsJsonSerializer.serializeObjectEnd(builder);
    // all these allocations kinda hurt
    return builder.toString().getBytes(UTF_8);
}
 
Example 7
Source File: ClassNameAndLineNumberConverter.java    From ns4_frame with Apache License 2.0 5 votes vote down vote up
protected String getFullyQualifiedName(ILoggingEvent event) {
	StackTraceElement[] cda = event.getCallerData();
	if (cda != null && cda.length > 0) {
		String loggerName = event.getLoggerName();
		int index = loggerName.indexOf(LogConstants.SPLIT_CATEGORY);
		loggerName = index != -1 ? loggerName.substring(0, index) : loggerName;
		/*String className = cda[cda.length - 1].getClassName();*/
		return loggerName /*+ LogConstants.CONNECT_CATEGORY
				+ className.substring(className.lastIndexOf(".") + 1) + "."
				+ Integer.toString(cda[cda.length - 1].getLineNumber())*/;
	}
	return CallerData.NA;
}
 
Example 8
Source File: ClassNameConverter.java    From ns4_frame with Apache License 2.0 5 votes vote down vote up
protected String getFullyQualifiedName(ILoggingEvent event) {

        StackTraceElement[] cda = event.getCallerData();
        if (cda != null) {
            if(cda.length > 1){
                return cda[1].getClassName();
            }else if(cda.length == 1){
                return cda[0].getClassName();
            }

        }
            return CallerData.NA;
    }
 
Example 9
Source File: GetLineNumberConverter.java    From ns4_frame with Apache License 2.0 5 votes vote down vote up
public String convert(ILoggingEvent le) {
    StackTraceElement[] cda = le.getCallerData();
    if (cda != null) {
        if(cda.length > 1){
            return Integer.toString(cda[1].getLineNumber());
        }else if(cda.length == 1){
            return Integer.toString(cda[0].getLineNumber());
        }

    }

    return CallerData.NA;
}
 
Example 10
Source File: GuiAppender.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
protected boolean isIgnoringLogRecord(ILoggingEvent event) {
  if (event.getLevel().levelInt < Level.INFO.levelInt) {
    if (event.hasCallerData()
      && event.getCallerData().length > 0) {
      for (String ignoreClass : ignoreClassesList) {
        if (StringUtils.equals(ignoreClass, event.getCallerData()[0].getClassName())) {
          return true;
        }
      }
    }
  }

  return false;
}
 
Example 11
Source File: LogbackUtil.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
public static void addCallerData(ILoggingEvent ev, LogDataBuilder builder) {
  if (ev.hasCallerData()) {
    final StackTraceElement[] callerData = ev.getCallerData();
    if (callerData.length > 0) {
      final StackTraceElement stackTraceElement = callerData[0];
      builder.withClass(stackTraceElement.getClassName());
      builder.withMethod(stackTraceElement.getMethodName());
      builder.withLineNumber(Integer.toString(stackTraceElement.getLineNumber()));
    }
  }
}
 
Example 12
Source File: GelfAppender.java    From logback-gelf-appender with Apache License 2.0 4 votes vote down vote up
@Override
protected void append(ILoggingEvent event) {

    if (event == null) {
        return;
    }

    // create a copy of the logging event to avoid passing exception stacktraces to GELF's short_message field
    LoggingEvent copy = new LoggingEvent();
    copy.setMessage(event.getMessage());
    copy.setLevel(event.getLevel());
    copy.setArgumentArray(event.getArgumentArray());
    copy.setLoggerName(event.getLoggerName());
    copy.setThreadName(event.getThreadName());
    copy.setTimeStamp(event.getTimeStamp());
    copy.setMDCPropertyMap(event.getMDCPropertyMap());

    final GelfMessageBuilder builder = new GelfMessageBuilder(this.layout.doLayout(copy), hostName).timestamp(
                event.getTimeStamp() / 1000d)
            .level(GelfMessageLevel.fromNumericLevel(toGelfNumericValue(event.getLevel())))
            .additionalField("loggerName", event.getLoggerName())
            .additionalField("threadName", event.getThreadName());

    final Marker marker = event.getMarker();

    if (marker != null) {
        builder.additionalField("marker", marker.getName());
    }

    if (includeMDC) {
        for (Map.Entry<String, String> entry : event.getMDCPropertyMap().entrySet()) {
            builder.additionalField(entry.getKey(), entry.getValue());
        }
    }

    final StackTraceElement[] callerData = event.getCallerData();

    if (includeSource && event.hasCallerData() && callerData.length > 0) {
        StackTraceElement source = callerData[0];

        builder.additionalField("sourceFileName", source.getFileName());
        builder.additionalField("sourceMethodName", source.getMethodName());
        builder.additionalField("sourceClassName", source.getClassName());
        builder.additionalField("sourceLineNumber", source.getLineNumber());
    }

    final IThrowableProxy thrown = event.getThrowableProxy();

    if (includeStackTrace && thrown != null) {
        String convertedThrowable = throwableConverter.convert(event);

        builder.additionalField("exceptionClass", thrown.getClassName());
        builder.additionalField("exceptionMessage", thrown.getMessage());
        builder.additionalField("exceptionStackTrace", convertedThrowable);

        builder.fullMessage(event.getFormattedMessage() + "\n\n" + convertedThrowable);
    } else {
        builder.fullMessage(event.getFormattedMessage());
    }

    if (includeLevelName) {
        builder.additionalField("levelName", event.getLevel().levelStr);
    }

    if (!additionalFields.isEmpty()) {
        builder.additionalFields(additionalFields);
    }

    if(!client.trySend(builder.build())) {
        addError("Failed to write log event to the GELF server using trySend");
    }
}
 
Example 13
Source File: DisruptorLogAppender.java    From NettyFileTransfer with Apache License 2.0 4 votes vote down vote up
protected void preprocess(ILoggingEvent eventObject) {
	eventObject.prepareForDeferredProcessing();
	if (includeCallerData)
		eventObject.getCallerData();
}
 
Example 14
Source File: DisruptorLogAppender.java    From High-concurrent-server with Apache License 2.0 4 votes vote down vote up
protected void preprocess(ILoggingEvent eventObject) {
	eventObject.prepareForDeferredProcessing();
	if (includeCallerData)
		eventObject.getCallerData();
}
 
Example 15
Source File: JSONEventLayout.java    From logback-redis-appender with Apache License 2.0 4 votes vote down vote up
/**
 * Formats a {@link ILoggingEvent} in conformity with the log4j.dtd.
 */
public synchronized String doLayout(ILoggingEvent event) {

	// Reset working buffer. If the buffer is too large, then we need a new
	// one in order to avoid the penalty of creating a large array.
	if (buf.capacity() > UPPER_LIMIT) {
		buf = new StringBuilder(DEFAULT_SIZE);
	} else {
		buf.setLength(0);
	}

	Map<String, String> mdc = event.getMDCPropertyMap();
	buf.append("{");
	appendKeyValue(buf, "source", source, mdc);
	buf.append(COMMA);
	appendKeyValue(buf, "host", sourceHost, mdc);
	buf.append(COMMA);
	appendKeyValue(buf, "path", sourcePath, mdc);
	buf.append(COMMA);
	appendKeyValue(buf, "type", type, mdc);
	buf.append(COMMA);
	appendKeyValue(buf, "tags", tags, mdc);
	buf.append(COMMA);
	appendKeyValue(buf, "message", event.getFormattedMessage(), null);
	buf.append(COMMA);
	appendKeyValue(buf, "@timestamp",
			df.format(new Date(event.getTimeStamp())), null);
	buf.append(COMMA);

	// ---- fields ----
	appendKeyValue(buf, "logger", event.getLoggerName(), null);
	buf.append(COMMA);
	appendKeyValue(buf, "level", event.getLevel().toString(), null);
	buf.append(COMMA);
	appendKeyValue(buf, "thread", event.getThreadName(), null);
	IThrowableProxy tp = event.getThrowableProxy();
	if (tp != null) {
		buf.append(COMMA);
		String throwable = ThrowableProxyUtil.asString(tp);
		appendKeyValue(buf, "throwable", throwable, null);
	}
	if (locationInfo) {
		StackTraceElement[] callerDataArray = event.getCallerData();
		if (callerDataArray != null
				&& callerDataArray.length > callerStackIdx) {
			buf.append(COMMA);
			buf.append("\"location\":{");
			StackTraceElement immediateCallerData = callerDataArray[callerStackIdx];
			appendKeyValue(buf, "class",
					immediateCallerData.getClassName(), null);
			buf.append(COMMA);
			appendKeyValue(buf, "method",
					immediateCallerData.getMethodName(), null);
			buf.append(COMMA);
			appendKeyValue(buf, "file", immediateCallerData.getFileName(),
					null);
			buf.append(COMMA);
			appendKeyValue(buf, "line",
					Integer.toString(immediateCallerData.getLineNumber()),
					null);
			buf.append("}");
		}
	}

	/*
	 * <log4j:properties> <log4j:data name="name" value="value"/>
	 * </log4j:properties>
	 */
	if (properties) {
		Map<String, String> propertyMap = event.getMDCPropertyMap();
		if ((propertyMap != null) && (propertyMap.size() != 0)) {
			Set<Entry<String, String>> entrySet = propertyMap.entrySet();
			buf.append(COMMA);
			buf.append("\"properties\":{");
			Iterator<Entry<String, String>> i = entrySet.iterator();
			while (i.hasNext()) {
				Entry<String, String> entry = i.next();
				appendKeyValue(buf, entry.getKey(), entry.getValue(), null);
				if (i.hasNext()) {
					buf.append(COMMA);
				}
			}
			buf.append("}");
		}
	}

	if(additionalFields != null) {
		for(AdditionalField field : additionalFields) {
			buf.append(COMMA);
			appendKeyValue(buf, field.getKey(), field.getValue(), mdc);
		}
	}

	buf.append("}");

	return buf.toString();
}