Java Code Examples for org.apache.logging.log4j.ThreadContext#ContextStack
The following examples show how to use
org.apache.logging.log4j.ThreadContext#ContextStack .
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: AbstractStringLayoutStringEncodingBenchmark.java From logging-log4j2 with Apache License 2.0 | 6 votes |
private static LogEvent createLogEvent(final Message message) { final Marker marker = null; final String fqcn = "com.mycom.myproject.mypackage.MyClass"; final org.apache.logging.log4j.Level level = org.apache.logging.log4j.Level.DEBUG; final Throwable t = null; final StringMap mdc = null; final ThreadContext.ContextStack ndc = null; final String threadName = null; final StackTraceElement location = null; final long timestamp = 12345678; return Log4jLogEvent.newBuilder() // .setLoggerName("name(ignored)") // .setMarker(marker) // .setLoggerFqcn(fqcn) // .setLevel(level) // .setMessage(message) // .setThrown(t) // .setContextData(mdc) // .setContextStack(ndc) // .setThreadName(threadName) // .setSource(location) // .setTimeMillis(timestamp) // .build(); }
Example 2
Source File: GelfLayoutBenchmark.java From logging-log4j2 with Apache License 2.0 | 6 votes |
private static LogEvent createLogEvent() { final Marker marker = null; final String fqcn = "com.mycom.myproject.mypackage.MyClass"; final org.apache.logging.log4j.Level level = org.apache.logging.log4j.Level.DEBUG; final Message message = new SimpleMessage(MESSAGE); final Throwable t = null; final StringMap mdc = null; final ThreadContext.ContextStack ndc = null; final String threadName = null; final StackTraceElement location = null; final long timestamp = 12345678; return Log4jLogEvent.newBuilder() // .setLoggerName("name(ignored)") // .setMarker(marker) // .setLoggerFqcn(fqcn) // .setLevel(level) // .setMessage(message) // .setThrown(t) // .setContextData(mdc) // .setContextStack(ndc) // .setThreadName(threadName) // .setSource(location) // .setTimeMillis(timestamp) // .build(); }
Example 3
Source File: ContextStackJsonAttributeConverterTest.java From logging-log4j2 with Apache License 2.0 | 6 votes |
@Test public void testConvert02() { final ThreadContext.ContextStack stack = new MutableThreadContextStack( Arrays.asList("key1", "value2", "my3")); final String converted = this.converter.convertToDatabaseColumn(stack); assertNotNull("The converted value should not be null.", converted); final ThreadContext.ContextStack reversed = this.converter .convertToEntityAttribute(converted); assertNotNull("The reversed value should not be null.", reversed); assertEquals("The reversed value is not correct.", stack.asList(), reversed.asList()); }
Example 4
Source File: Log4jLogEvent.java From logging-log4j2 with Apache License 2.0 | 6 votes |
private Log4jLogEvent(final String loggerName, final Marker marker, final String loggerFQCN, final Level level, final Message message, final Throwable thrown, final ThrowableProxy thrownProxy, final StringMap contextData, final ThreadContext.ContextStack contextStack, final long threadId, final String threadName, final int threadPriority, final StackTraceElement source, final long nanoTime) { this.loggerName = loggerName; this.marker = marker; this.loggerFqcn = loggerFQCN; this.level = level == null ? Level.OFF : level; // LOG4J2-462, LOG4J2-465 this.message = message; this.thrown = thrown; this.thrownProxy = thrownProxy; this.contextData = contextData == null ? ContextDataFactory.createContextData() : contextData; this.contextStack = contextStack == null ? ThreadContext.EMPTY_STACK : contextStack; this.threadId = threadId; this.threadName = threadName; this.threadPriority = threadPriority; this.source = source; if (message instanceof LoggerNameAwareMessage) { ((LoggerNameAwareMessage) message).setLoggerName(loggerName); } this.nanoTime = nanoTime; }
Example 5
Source File: ContextStackAttributeConverterTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@Test public void testConvertToDatabaseColumn02() { final ThreadContext.ContextStack stack = new MutableThreadContextStack( Arrays.asList("key1", "value2", "my3")); assertEquals("The converted value is not correct.", "key1\nvalue2\nmy3", this.converter.convertToDatabaseColumn(stack)); }
Example 6
Source File: ContextStackAttributeConverterTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@Test public void testConvertToDatabaseColumn01() { final ThreadContext.ContextStack stack = new MutableThreadContextStack( Arrays.asList("value1", "another2")); assertEquals("The converted value is not correct.", "value1\nanother2", this.converter.convertToDatabaseColumn(stack)); }
Example 7
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 8
Source File: Log4jLogEvent.java From logging-log4j2 with Apache License 2.0 | 5 votes |
private Log4jLogEvent(final String loggerName, final Marker marker, final String loggerFQCN, final Level level, final Message message, final Throwable thrown, final ThrowableProxy thrownProxy, final StringMap contextData, final ThreadContext.ContextStack contextStack, final long threadId, final String threadName, final int threadPriority, final StackTraceElement source, final Clock clock, final long nanoTime) { this(loggerName, marker, loggerFQCN, level, message, thrown, thrownProxy, contextData, contextStack, threadId, threadName, threadPriority, source, nanoTime); if (message instanceof TimestampMessage) { instant.initFromEpochMilli(((TimestampMessage) message).getTimestamp(), 0); } else { instant.initFrom(clock); } }
Example 9
Source File: ContextStackAttributeConverter.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@Override public String convertToDatabaseColumn(final ThreadContext.ContextStack contextStack) { if (contextStack == null) { return null; } final StringBuilder builder = new StringBuilder(); for (final String value : contextStack.asList()) { if (builder.length() > 0) { builder.append('\n'); } builder.append(value); } return builder.toString(); }
Example 10
Source File: Log4jLogEvent.java From logging-log4j2 with Apache License 2.0 | 4 votes |
/** * Returns an immutable copy of the ThreadContext stack. * @return The context Stack. */ @Override public ThreadContext.ContextStack getContextStack() { return contextStack; }
Example 11
Source File: NoSqlDatabaseManagerTest.java From logging-log4j2 with Apache License 2.0 | 4 votes |
@Test public void testWriteInternal02() { given(connection.isClosed()).willReturn(false); given(message.getFormattedMessage()).willReturn("Another cool message 02."); try (final NoSqlDatabaseManager<?> manager = NoSqlDatabaseManager.getNoSqlDatabaseManager("name", 0, provider)) { manager.startup(); manager.connectAndStart(); then(provider).should().getConnection(); final RuntimeException exception = new RuntimeException("This is something cool!"); final Map<String, String> context = new HashMap<>(); context.put("hello", "world"); context.put("user", "pass"); ThreadContext.push("message1"); ThreadContext.push("stack2"); final ThreadContext.ContextStack stack = ThreadContext.getImmutableStack(); ThreadContext.clearStack(); final LogEvent event = Log4jLogEvent.newBuilder() .setLevel(Level.DEBUG) .setLoggerName("com.foo.NoSQLDbTest.testWriteInternal02") .setMessage(message) .setSource(new StackTraceElement("com.bar.Foo", "anotherMethod03", "Foo.java", 9)) .setMarker(MarkerManager.getMarker("LoneMarker")) .setThreadId(1L) .setThreadName("AnotherThread-B") .setThreadPriority(1) .setTimeMillis(987654321564L) .setThrown(exception) .setContextData(ContextDataFactory.createContextData(context)) .setContextStack(stack) .build(); manager.writeInternal(event, null); then(connection).should().insertObject(captor.capture()); final NoSqlObject<Map<String, Object>> inserted = captor.getValue(); assertNotNull("The inserted value should not be null.", inserted); final Map<String, Object> object = inserted.unwrap(); assertNotNull("The unwrapped object should not be null.", object); assertEquals("The level is not correct.", Level.DEBUG, object.get("level")); assertEquals("The logger is not correct.", "com.foo.NoSQLDbTest.testWriteInternal02", object.get("loggerName")); assertEquals("The message is not correct.", "Another cool message 02.", object.get("message")); assertEquals("The thread is not correct.", "AnotherThread-B", object.get("threadName")); assertEquals("The millis is not correct.", 987654321564L, object.get("millis")); assertEquals("The date is not correct.", 987654321564L, ((Date) object.get("date")).getTime()); assertTrue("The source should be a map.", object.get("source") instanceof Map); @SuppressWarnings("unchecked") final Map<String, Object> source = (Map<String, Object>) object.get("source"); assertEquals("The class is not correct.", "com.bar.Foo", source.get("className")); assertEquals("The method is not correct.", "anotherMethod03", source.get("methodName")); assertEquals("The file name is not correct.", "Foo.java", source.get("fileName")); assertEquals("The line number is not correct.", 9, source.get("lineNumber")); assertTrue("The marker should be a map.", object.get("marker") instanceof Map); @SuppressWarnings("unchecked") final Map<String, Object> marker = (Map<String, Object>) object.get("marker"); assertEquals("The marker name is not correct.", "LoneMarker", marker.get("name")); assertNull("The marker parent should be null.", marker.get("parent")); assertTrue("The thrown should be a map.", object.get("thrown") instanceof Map); @SuppressWarnings("unchecked") final Map<String, Object> thrown = (Map<String, Object>) object.get("thrown"); assertEquals("The thrown type is not correct.", "java.lang.RuntimeException", thrown.get("type")); assertEquals("The thrown message is not correct.", "This is something cool!", thrown.get("message")); assertTrue("The thrown stack trace should be a list.", thrown.get("stackTrace") instanceof List); @SuppressWarnings("unchecked") final List<Map<String, Object>> stackTrace = (List<Map<String, Object>>) thrown.get("stackTrace"); assertEquals("The thrown stack trace length is not correct.", exception.getStackTrace().length, stackTrace.size()); for (int i = 0; i < exception.getStackTrace().length; i++) { final StackTraceElement e1 = exception.getStackTrace()[i]; final Map<String, Object> e2 = stackTrace.get(i); assertEquals("Element class name [" + i + "] is not correct.", e1.getClassName(), e2.get("className")); assertEquals("Element method name [" + i + "] is not correct.", e1.getMethodName(), e2.get("methodName")); assertEquals("Element file name [" + i + "] is not correct.", e1.getFileName(), e2.get("fileName")); assertEquals("Element line number [" + i + "] is not correct.", e1.getLineNumber(), e2.get("lineNumber")); } assertNull("The thrown should have no cause.", thrown.get("cause")); assertTrue("The context map should be a map.", object.get("contextMap") instanceof Map); assertEquals("The context map is not correct.", context, object.get("contextMap")); assertTrue("The context stack should be list.", object.get("contextStack") instanceof List); assertEquals("The context stack is not correct.", stack.asList(), object.get("contextStack")); } }
Example 12
Source File: MutableLogEvent.java From logging-log4j2 with Apache License 2.0 | 4 votes |
@Override public ThreadContext.ContextStack getContextStack() { return contextStack; }
Example 13
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 14
Source File: AbstractJacksonLayout.java From logging-log4j2 with Apache License 2.0 | 4 votes |
@Override public ThreadContext.ContextStack getContextStack() { return event.getContextStack(); }
Example 15
Source File: MutableLogEvent.java From logging-log4j2 with Apache License 2.0 | 4 votes |
public void setContextStack(final ThreadContext.ContextStack contextStack) { this.contextStack = contextStack; }
Example 16
Source File: TestBaseEntity.java From logging-log4j2 with Apache License 2.0 | 4 votes |
@Override @Transient public ThreadContext.ContextStack getContextStack() { return this.getWrappedEvent().getContextStack(); }
Example 17
Source File: Log4jLogEvent.java From logging-log4j2 with Apache License 2.0 | 4 votes |
public Builder setContextStack(final ThreadContext.ContextStack contextStack) { this.contextStack = contextStack; return this; }
Example 18
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 19
Source File: AbstractLogEventWrapperEntity.java From logging-log4j2 with Apache License 2.0 | 2 votes |
/** * A no-op mutator to satisfy JPA requirements, as this entity is write-only. * * @param contextStack Ignored. */ @SuppressWarnings("unused") public void setContextStack(final ThreadContext.ContextStack contextStack) { // this entity is write-only }
Example 20
Source File: LogEvent.java From logging-log4j2 with Apache License 2.0 | 2 votes |
/** * Gets the context stack (also known as Nested Diagnostic Context or NDC). * * @return The context stack, never {@code null}. */ ThreadContext.ContextStack getContextStack();