Java Code Examples for org.apache.logging.log4j.core.LogEvent#getContextStack()
The following examples show how to use
org.apache.logging.log4j.core.LogEvent#getContextStack() .
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: Log4jLogEvent.java From logging-log4j2 with Apache License 2.0 | 6 votes |
public LogEventProxy(final LogEvent event, final boolean includeLocation) { this.loggerFQCN = event.getLoggerFqcn(); this.marker = event.getMarker(); this.level = event.getLevel(); this.loggerName = event.getLoggerName(); final Message temp = event.getMessage(); message = temp instanceof ReusableMessage ? memento((ReusableMessage) temp) : temp; this.timeMillis = event.getInstant().getEpochMillisecond(); this.nanoOfMillisecond = event.getInstant().getNanoOfMillisecond(); this.thrown = event.getThrown(); this.thrownProxy = event.getThrownProxy(); this.contextData = memento(event.getContextData()); this.contextStack = event.getContextStack(); this.source = includeLocation ? event.getSource() : null; this.threadId = event.getThreadId(); this.threadName = event.getThreadName(); this.threadPriority = event.getThreadPriority(); this.isLocationRequired = includeLocation; this.isEndOfBatch = event.isEndOfBatch(); this.nanoTime = event.getNanoTime(); }
Example 2
Source File: MutableLogEvent.java From logging-log4j2 with Apache License 2.0 | 6 votes |
/** * Initialize the fields of this {@code MutableLogEvent} from another event. * Similar in purpose and usage as {@link org.apache.logging.log4j.core.impl.Log4jLogEvent.LogEventProxy}, * but a mutable version. * <p> * This method is used on async logger ringbuffer slots holding MutableLogEvent objects in each slot. * </p> * * @param event the event to copy data from */ public void initFrom(final LogEvent event) { this.loggerFqcn = event.getLoggerFqcn(); this.marker = event.getMarker(); this.level = event.getLevel(); this.loggerName = event.getLoggerName(); this.thrown = event.getThrown(); this.thrownProxy = event.getThrownProxy(); this.instant.initFrom(event.getInstant()); // NOTE: this ringbuffer event SHOULD NOT keep a reference to the specified // thread-local MutableLogEvent's context data, because then two threads would call // ReadOnlyStringMap.clear() on the same shared instance, resulting in data corruption. this.contextData.putAll(event.getContextData()); this.contextStack = event.getContextStack(); this.source = event.isIncludeLocation() ? event.getSource() : null; this.threadId = event.getThreadId(); this.threadName = event.getThreadName(); this.threadPriority = event.getThreadPriority(); this.endOfBatch = event.isEndOfBatch(); this.includeLocation = event.isIncludeLocation(); this.nanoTime = event.getNanoTime(); setMessage(event.getMessage()); }
Example 3
Source File: RollbarAppender.java From rollbar-java with MIT License | 5 votes |
private List<String> getNdc(LogEvent event) { if (event.getContextStack() == null || event.getContextStack().size() == 0) { return null; } return event.getContextStack().asList(); }
Example 4
Source File: ThreadContextStackResolver.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@Override public void resolve( final LogEvent logEvent, final JsonWriter jsonWriter) { final ThreadContext.ContextStack contextStack = logEvent.getContextStack(); if (contextStack.getDepth() == 0) { jsonWriter.writeNull(); return; } boolean arrayStarted = false; for (final String contextStackItem : contextStack.asList()) { final boolean matched = itemPattern == null || itemPattern.matcher(contextStackItem).matches(); if (matched) { if (arrayStarted) { jsonWriter.writeSeparator(); } else { jsonWriter.writeArrayStart(); arrayStarted = true; } jsonWriter.writeString(contextStackItem); } } if (arrayStarted) { jsonWriter.writeArrayEnd(); } else { jsonWriter.writeNull(); } }
Example 5
Source File: CustomHTMLLayout.java From audit-log-plugin with MIT License | 4 votes |
/** * Formats as a String. * * @param event The Logging Event. * @return A String containing the LogEvent as HTML. */ @Override public String toSerializable(final LogEvent event) { final StringBuilder sbuf = getStringBuilder(); sbuf.append(Strings.LINE_SEPARATOR).append("<tr>").append(Strings.LINE_SEPARATOR); sbuf.append("<td>"); sbuf.append(DateTimeHelper.formatDateISO(event.getTimeMillis())); sbuf.append("</td>").append(Strings.LINE_SEPARATOR); final String escapedThread = Transform.escapeHtmlTags(event.getThreadName()); sbuf.append("<td title=\"").append(escapedThread).append(" thread\">"); sbuf.append(escapedThread); sbuf.append("</td>").append(Strings.LINE_SEPARATOR); sbuf.append("<td title=\"Level\""); if (event.getLevel().equals(Level.DEBUG)) { sbuf.append(" class=\"debug\">"); sbuf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel()))); } else if (event.getLevel().isMoreSpecificThan(Level.WARN)) { sbuf.append(" class=\"warn\">"); sbuf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel()))); } else { sbuf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel()))); } sbuf.append("</td>").append(Strings.LINE_SEPARATOR); String escapedLogger = Transform.escapeHtmlTags(event.getLoggerName()); if (Strings.isEmpty(escapedLogger)) { escapedLogger = LoggerConfig.ROOT; } sbuf.append("<td title=\"").append(escapedLogger).append(" logger\">"); sbuf.append(escapedLogger); sbuf.append("</td>").append(Strings.LINE_SEPARATOR); if (locationInfo) { final StackTraceElement element = event.getSource(); sbuf.append("<td>"); sbuf.append(Transform.escapeHtmlTags(element.getFileName())); sbuf.append(':'); sbuf.append(element.getLineNumber()); sbuf.append("</td>").append(Strings.LINE_SEPARATOR); } sbuf.append("<td title=\"Message\">"); sbuf.append(Transform.escapeHtmlTags(event.getMessage().getFormattedMessage()).replaceAll(REGEXP, "<br />")); sbuf.append("</td>").append(Strings.LINE_SEPARATOR); sbuf.append("</tr>").append(Strings.LINE_SEPARATOR); if (event.getContextStack() != null && !event.getContextStack().isEmpty()) { sbuf.append("<tr><td class=\"context\" "); sbuf.append("colspan=\"6\" "); sbuf.append("title=\"Nested Diagnostic Context\">"); sbuf.append("NDC: ").append(Transform.escapeHtmlTags(event.getContextStack().toString())); sbuf.append("</td></tr>").append(Strings.LINE_SEPARATOR); } if (event.getContextData() != null && !event.getContextData().isEmpty()) { sbuf.append("<tr><td class=\"context\" "); sbuf.append("colspan=\"6\" "); sbuf.append("title=\"Mapped Diagnostic Context\">"); sbuf.append("MDC: ").append(Transform.escapeHtmlTags(event.getContextData().toMap().toString())); sbuf.append("</td></tr>").append(Strings.LINE_SEPARATOR); } final Throwable throwable = event.getThrown(); if (throwable != null) { sbuf.append("<tr><td class=\"throw\" "); sbuf.append("colspan=\"6\">"); appendThrowableAsHtml(throwable, sbuf); sbuf.append("</td></tr>").append(Strings.LINE_SEPARATOR); } return sbuf.toString(); }
Example 6
Source File: LoggingEventJsonSerde.java From samza with Apache License 2.0 | 4 votes |
/** * Encodes a LoggingEvent into a HashMap using the logstash JSON format. * * @param loggingEvent * The LoggingEvent to encode. * @param includeLocationInfo * Whether to include LocationInfo in the map, or not. * @return A Map representing the LoggingEvent, which is suitable to be * serialized by a JSON encoder such as Jackson. */ @SuppressWarnings("rawtypes") public static Map<String, Object> encodeToMap(LogEvent loggingEvent, boolean includeLocationInfo) { Map<String, Object> logstashEvent = new LoggingEventJsonSerde.LoggingEventMap(); String threadName = loggingEvent.getThreadName(); long timestamp = loggingEvent.getTimeMillis(); HashMap<String, Object> exceptionInformation = new HashMap<String, Object>(); Map mdc = loggingEvent.getContextData().toMap(); ThreadContext.ContextStack ndc = loggingEvent.getContextStack(); logstashEvent.put("@version", VERSION); logstashEvent.put("@timestamp", dateFormat(timestamp)); logstashEvent.put("source_host", getHostname()); logstashEvent.put("message", loggingEvent.getMessage()); if (loggingEvent.getThrown() != null) { final Throwable throwableInformation = loggingEvent.getThrown(); if (throwableInformation.getClass().getCanonicalName() != null) { exceptionInformation.put("exception_class", throwableInformation.getClass().getCanonicalName()); } if (throwableInformation.getMessage() != null) { exceptionInformation.put("exception_message", throwableInformation.getMessage()); } if (throwableInformation.getMessage() != null) { StringBuilder stackTrace = new StringBuilder(ExceptionUtils.getStackTrace(throwableInformation)); exceptionInformation.put("stacktrace", stackTrace); } logstashEvent.put("exception", exceptionInformation); } if (includeLocationInfo) { StackTraceElement info = loggingEvent.getSource(); logstashEvent.put("file", info.getFileName()); logstashEvent.put("line_number", info.getLineNumber()); logstashEvent.put("class", info.getClassName()); logstashEvent.put("method", info.getMethodName()); } logstashEvent.put("logger_name", loggingEvent.getLoggerName()); logstashEvent.put("mdc", mdc); logstashEvent.put("ndc", ndc); logstashEvent.put("level", loggingEvent.getLevel().toString()); logstashEvent.put("thread_name", threadName); return logstashEvent; }
Example 7
Source File: GelfAppender.java From log4j2-gelf with Apache License 2.0 | 4 votes |
@Override public void append(LogEvent event) { final Layout<? extends Serializable> layout = getLayout(); final String formattedMessage; if (layout == null) { formattedMessage = event.getMessage().getFormattedMessage(); } else { formattedMessage = new String(layout.toByteArray(event), StandardCharsets.UTF_8); } final GelfMessageBuilder builder = new GelfMessageBuilder(formattedMessage, hostName) .timestamp(event.getTimeMillis() / 1000d) .level(GelfMessageLevel.fromNumericLevel(Severity.getSeverity(event.getLevel()).getCode())) .additionalField("loggerName", event.getLoggerName()) .additionalField("threadName", event.getThreadName()); final Marker marker = event.getMarker(); if (marker != null) { builder.additionalField("marker", marker.getName()); } if (includeThreadContext) { for (Map.Entry<String, String> entry : event.getContextMap().entrySet()) { builder.additionalField(entry.getKey(), entry.getValue()); } // Guard against https://issues.apache.org/jira/browse/LOG4J2-1530 final ThreadContext.ContextStack contextStack = event.getContextStack(); if (contextStack != null) { final List<String> contextStackItems = contextStack.asList(); if (contextStackItems != null && !contextStackItems.isEmpty()) { builder.additionalField("contextStack", contextStackItems.toString()); } } } if (includeSource) { final StackTraceElement source = event.getSource(); if (source != null) { builder.additionalField("sourceFileName", source.getFileName()); builder.additionalField("sourceMethodName", source.getMethodName()); builder.additionalField("sourceClassName", source.getClassName()); builder.additionalField("sourceLineNumber", source.getLineNumber()); } } @SuppressWarnings("all") final Throwable thrown = event.getThrown(); if (includeStackTrace && thrown != null) { String stackTrace; if (includeExceptionCause) { final StringWriter stringWriter = new StringWriter(); final PrintWriter printWriter = new PrintWriter(stringWriter); thrown.printStackTrace(printWriter); stackTrace = stringWriter.toString(); } else { stackTrace = getSimpleStacktraceAsString(thrown); } builder.additionalField("exceptionClass", thrown.getClass().getCanonicalName()); builder.additionalField("exceptionMessage", thrown.getMessage()); builder.additionalField("exceptionStackTrace", stackTrace); builder.fullMessage(formattedMessage); } if (!additionalFields.isEmpty()) { builder.additionalFields(additionalFields); } final GelfMessage gelfMessage = builder.build(); try { final boolean sent = client.trySend(gelfMessage); if (!sent) { LOG.debug("Couldn't send message: {}", gelfMessage); } } catch (Exception e) { throw new AppenderLoggingException("failed to write log event to GELF server: " + e.getMessage(), e); } }
Example 8
Source File: ThreadContextStackResolver.java From logging-log4j2 with Apache License 2.0 | 4 votes |
@Override public boolean isResolvable(final LogEvent logEvent) { final ThreadContext.ContextStack contextStack = logEvent.getContextStack(); return contextStack.getDepth() > 0; }
Example 9
Source File: Log4jLogEvent.java From logging-log4j2 with Apache License 2.0 | 4 votes |
public Builder(final LogEvent other) { Objects.requireNonNull(other); if (other instanceof RingBufferLogEvent) { ((RingBufferLogEvent) other).initializeBuilder(this); return; } if (other instanceof MutableLogEvent) { ((MutableLogEvent) other).initializeBuilder(this); return; } this.loggerFqcn = other.getLoggerFqcn(); this.marker = other.getMarker(); this.level = other.getLevel(); this.loggerName = other.getLoggerName(); this.message = other.getMessage(); this.instant.initFrom(other.getInstant()); this.thrown = other.getThrown(); this.contextStack = other.getContextStack(); this.includeLocation = other.isIncludeLocation(); this.endOfBatch = other.isEndOfBatch(); this.nanoTime = other.getNanoTime(); // Avoid unnecessarily initializing thrownProxy, threadName and source if possible if (other instanceof Log4jLogEvent) { final Log4jLogEvent evt = (Log4jLogEvent) other; this.contextData = evt.contextData; this.thrownProxy = evt.thrownProxy; this.source = evt.source; this.threadId = evt.threadId; this.threadName = evt.threadName; this.threadPriority = evt.threadPriority; } else { if (other.getContextData() instanceof StringMap) { this.contextData = (StringMap) other.getContextData(); } else { if (this.contextData.isFrozen()) { this.contextData = ContextDataFactory.createContextData(); } else { this.contextData.clear(); } this.contextData.putAll(other.getContextData()); } this.thrownProxy = other.getThrownProxy(); this.source = other.getSource(); this.threadId = other.getThreadId(); this.threadName = other.getThreadName(); this.threadPriority = other.getThreadPriority(); } }
Example 10
Source File: NoSqlDatabaseManager.java From logging-log4j2 with Apache License 2.0 | 4 votes |
private void setFields(final LogEvent event, final NoSqlObject<W> entity) { entity.set("level", event.getLevel()); entity.set("loggerName", event.getLoggerName()); entity.set("message", event.getMessage() == null ? null : event.getMessage().getFormattedMessage()); final StackTraceElement source = event.getSource(); if (source == null) { entity.set("source", (Object) null); } else { entity.set("source", this.convertStackTraceElement(source)); } final Marker marker = event.getMarker(); if (marker == null) { entity.set("marker", (Object) null); } else { entity.set("marker", buildMarkerEntity(marker)); } entity.set("threadId", event.getThreadId()); entity.set("threadName", event.getThreadName()); entity.set("threadPriority", event.getThreadPriority()); entity.set("millis", event.getTimeMillis()); entity.set("date", new java.util.Date(event.getTimeMillis())); @SuppressWarnings("ThrowableResultOfMethodCallIgnored") Throwable thrown = event.getThrown(); if (thrown == null) { entity.set("thrown", (Object) null); } else { final NoSqlObject<W> originalExceptionEntity = this.connection.createObject(); NoSqlObject<W> exceptionEntity = originalExceptionEntity; exceptionEntity.set("type", thrown.getClass().getName()); exceptionEntity.set("message", thrown.getMessage()); exceptionEntity.set("stackTrace", this.convertStackTrace(thrown.getStackTrace())); while (thrown.getCause() != null) { thrown = thrown.getCause(); final NoSqlObject<W> causingExceptionEntity = this.connection.createObject(); causingExceptionEntity.set("type", thrown.getClass().getName()); causingExceptionEntity.set("message", thrown.getMessage()); causingExceptionEntity.set("stackTrace", this.convertStackTrace(thrown.getStackTrace())); exceptionEntity.set("cause", causingExceptionEntity); exceptionEntity = causingExceptionEntity; } entity.set("thrown", originalExceptionEntity); } final ReadOnlyStringMap contextMap = event.getContextData(); if (contextMap == null) { entity.set("contextMap", (Object) null); } else { final NoSqlObject<W> contextMapEntity = this.connection.createObject(); contextMap.forEach(new BiConsumer<String, String>() { @Override public void accept(final String key, final String val) { contextMapEntity.set(key, val); } }); entity.set("contextMap", contextMapEntity); } final ThreadContext.ContextStack contextStack = event.getContextStack(); if (contextStack == null) { entity.set("contextStack", (Object) null); } else { entity.set("contextStack", contextStack.asList().toArray()); } }
Example 11
Source File: HtmlLayout.java From logging-log4j2 with Apache License 2.0 | 4 votes |
/** * Formats as a String. * * @param event The Logging Event. * @return A String containing the LogEvent as HTML. */ @Override public String toSerializable(final LogEvent event) { final StringBuilder sbuf = getStringBuilder(); sbuf.append(Strings.LINE_SEPARATOR).append("<tr>").append(Strings.LINE_SEPARATOR); sbuf.append("<td>"); sbuf.append(event.getTimeMillis() - jvmStartTime); sbuf.append("</td>").append(Strings.LINE_SEPARATOR); final String escapedThread = Transform.escapeHtmlTags(event.getThreadName()); sbuf.append("<td title=\"").append(escapedThread).append(" thread\">"); sbuf.append(escapedThread); sbuf.append("</td>").append(Strings.LINE_SEPARATOR); sbuf.append("<td title=\"Level\">"); if (event.getLevel().equals(Level.DEBUG)) { sbuf.append("<font color=\"#339933\">"); sbuf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel()))); sbuf.append("</font>"); } else if (event.getLevel().isMoreSpecificThan(Level.WARN)) { sbuf.append("<font color=\"#993300\"><strong>"); sbuf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel()))); sbuf.append("</strong></font>"); } else { sbuf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel()))); } sbuf.append("</td>").append(Strings.LINE_SEPARATOR); String escapedLogger = Transform.escapeHtmlTags(event.getLoggerName()); if (Strings.isEmpty(escapedLogger)) { escapedLogger = LoggerConfig.ROOT; } sbuf.append("<td title=\"").append(escapedLogger).append(" logger\">"); sbuf.append(escapedLogger); sbuf.append("</td>").append(Strings.LINE_SEPARATOR); if (locationInfo) { final StackTraceElement element = event.getSource(); sbuf.append("<td>"); sbuf.append(Transform.escapeHtmlTags(element.getFileName())); sbuf.append(':'); sbuf.append(element.getLineNumber()); sbuf.append("</td>").append(Strings.LINE_SEPARATOR); } sbuf.append("<td title=\"Message\">"); sbuf.append(Transform.escapeHtmlTags(event.getMessage().getFormattedMessage()).replaceAll(REGEXP, "<br />")); sbuf.append("</td>").append(Strings.LINE_SEPARATOR); sbuf.append("</tr>").append(Strings.LINE_SEPARATOR); if (event.getContextStack() != null && !event.getContextStack().isEmpty()) { sbuf.append("<tr><td bgcolor=\"#EEEEEE\" style=\"font-size : ").append(fontSize); sbuf.append(";\" colspan=\"6\" "); sbuf.append("title=\"Nested Diagnostic Context\">"); sbuf.append("NDC: ").append(Transform.escapeHtmlTags(event.getContextStack().toString())); sbuf.append("</td></tr>").append(Strings.LINE_SEPARATOR); } if (event.getContextData() != null && !event.getContextData().isEmpty()) { sbuf.append("<tr><td bgcolor=\"#EEEEEE\" style=\"font-size : ").append(fontSize); sbuf.append(";\" colspan=\"6\" "); sbuf.append("title=\"Mapped Diagnostic Context\">"); sbuf.append("MDC: ").append(Transform.escapeHtmlTags(event.getContextData().toMap().toString())); sbuf.append("</td></tr>").append(Strings.LINE_SEPARATOR); } final Throwable throwable = event.getThrown(); if (throwable != null) { sbuf.append("<tr><td bgcolor=\"#993300\" style=\"color:White; font-size : ").append(fontSize); sbuf.append(";\" colspan=\"6\">"); appendThrowableAsHtml(throwable, sbuf); sbuf.append("</td></tr>").append(Strings.LINE_SEPARATOR); } return sbuf.toString(); }