/** * Prepare log event log event. * * @param logEvent the log event * @return the log event */ public static LogEvent prepareLogEvent(final LogEvent logEvent) { final String messageModified = TicketIdSanitizationUtils.sanitize(logEvent.getMessage().getFormattedMessage()); final Message message = new SimpleMessage(messageModified); final LogEvent newLogEvent = Log4jLogEvent.newBuilder() .setLevel(logEvent.getLevel()) .setLoggerName(logEvent.getLoggerName()) .setLoggerFqcn(logEvent.getLoggerFqcn()) .setContextMap(logEvent.getContextMap()) .setContextStack(logEvent.getContextStack()) .setEndOfBatch(logEvent.isEndOfBatch()) .setIncludeLocation(logEvent.isIncludeLocation()) .setMarker(logEvent.getMarker()) .setMessage(message) .setNanoTime(logEvent.getNanoTime()) .setSource(logEvent.getSource()) .setThreadName(logEvent.getThreadName()) .setThrownProxy(logEvent.getThrownProxy()) .setThrown(logEvent.getThrown()) .setTimeMillis(logEvent.getTimeMillis()) .build(); return newLogEvent; }
@Test public void test_lineSeparator_suffix() { // Create the log event. SimpleMessage message = new SimpleMessage("Hello, World!"); LogEvent logEvent = Log4jLogEvent .newBuilder() .setLoggerName(LogstashLayoutTest.class.getSimpleName()) .setLevel(Level.INFO) .setMessage(message) .build(); // Check line separators. SoftAssertions assertions = new SoftAssertions(); test_lineSeparator_suffix(logEvent, true, assertions); test_lineSeparator_suffix(logEvent, false, assertions); assertions.assertAll(); }
@Override protected Object newEvent(LogDetails logDetails) { final Message message = new SimpleMessage(logDetails.getLogMessage()); final StringMap contextData; if (!logDetails.getMdc().isEmpty()) { contextData = ContextDataFactory.createContextData(); logDetails.getMdc().entrySet().forEach(it -> contextData.putValue(it.getKey(), it.getValue())); } else { contextData = null; } Log4jLogEvent.Builder builder = Log4jLogEvent.newBuilder().setLoggerName(logDetails.getClassName()) .setTimeMillis(logDetails.getTimeMillis()).setLevel(Level.DEBUG).setContextData(contextData) .setIncludeLocation(logDetails.isLocationInfo()).setLoggerFqcn(logDetails.getClassName()).setMessage(message); if (logDetails.isLocationInfo()) { builder.setSource(new StackTraceElement(logDetails.getClassName(), logDetails.getMethodName(), logDetails.getFileName(), logDetails.getLineNumber())); } if (logDetails.getException() != null) { builder.setThrown(logDetails.getException()); } return builder.build(); }
@Test(enabled = false) public void testKinesisPutRecords() throws Exception { List<LogEvent> logEventList = Collections.singletonList( Log4jLogEvent.createEvent("foobar", null, "foo.bar", Level.ERROR, null, null, null, null, null, "tname", null, 12345)); Collection<PutRecordsRequestEntry> records = new ArrayList<>(); for (LogEvent logEvent : logEventList) { String toJson = objectMapper.writeValueAsString(logEvent); PutRecordsRequestEntry putRecordsRequestEntry = new PutRecordsRequestEntry() .withData(ByteBuffer.wrap(toJson.getBytes())) .withPartitionKey("testKinesisPutRecords"); records.add(putRecordsRequestEntry); } PutRecordsRequest putRecordsRequest = new PutRecordsRequest(); putRecordsRequest.setRecords(records); putRecordsRequest.setStreamName(awsStreamName); PutRecordsResult putRecordsResult = client.putRecords(putRecordsRequest); System.out.println(putRecordsResult.toString()); }
@Test public void testAppend_Simple() { SystemdJournalAppender journalAppender = new SystemdJournalAppender("Journal", null, null, false, journalLibrary, false, false, false, false, false, false, null, null); Message message = mock(Message.class); when(message.getFormattedMessage()).thenReturn("some message"); LogEvent event = new Log4jLogEvent.Builder().setMessage(message).setLevel(Level.INFO).build(); journalAppender.append(event); List<Object> expectedArgs = new ArrayList<>(); expectedArgs.add("some message"); expectedArgs.add("PRIORITY=%d"); expectedArgs.add(6); expectedArgs.add(null); verify(journalLibrary).sd_journal_send("MESSAGE=%s", expectedArgs.toArray()); }
@Test public void testAppend_DoNotLogException() { SystemdJournalAppender journalAppender = new SystemdJournalAppender("Journal", null, null, false, journalLibrary, false, false, false, false, false, false, null, null); Message message = mock(Message.class); when(message.getFormattedMessage()).thenReturn("some message"); LogEvent event = new Log4jLogEvent.Builder() // .setMessage(message)// .setLoggerFqcn(journalAppender.getClass().getName())// .setThrown(new Throwable()) // .setLevel(Level.INFO).build(); event.setIncludeLocation(true); journalAppender.append(event); List<Object> expectedArgs = new ArrayList<>(); expectedArgs.add("some message"); expectedArgs.add("PRIORITY=%d"); expectedArgs.add(6); expectedArgs.add(null); verify(journalLibrary).sd_journal_send("MESSAGE=%s", expectedArgs.toArray()); }
@Test public void testThresholds() throws Exception { RegexFilter filter = RegexFilter.createFilter(".* test .*", null, false, null, null); filter.start(); assertTrue(filter.isStarted()); assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.DEBUG, null, (Object) "This is a test message", (Throwable) null)); assertSame(Filter.Result.DENY, filter.filter(null, Level.ERROR, null, (Object) "This is not a test", (Throwable) null)); LogEvent event = Log4jLogEvent.newBuilder() // .setLevel(Level.DEBUG) // .setMessage(new SimpleMessage("Another test message")) // .build(); assertSame(Filter.Result.NEUTRAL, filter.filter(event)); event = Log4jLogEvent.newBuilder() // .setLevel(Level.ERROR) // .setMessage(new SimpleMessage("test")) // .build(); assertSame(Filter.Result.DENY, filter.filter(event)); filter = RegexFilter.createFilter(null, null, false, null, null); assertNull(filter); }
@Test public void testSuffixFromNormalPattern() { final String suffix = "suffix(%mdc{key})"; ThreadContext.put("key", "test suffix "); final String[] options = {suffix}; final ExtendedThrowablePatternConverter converter = ExtendedThrowablePatternConverter.newInstance(null, options); final Throwable cause = new NullPointerException("null pointer"); final Throwable parent = new IllegalArgumentException("IllegalArgument", cause); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("testLogger") // .setLoggerFqcn(this.getClass().getName()) // .setLevel(Level.DEBUG) // .setMessage(new SimpleMessage("test exception")) // .setThrown(parent).build(); final StringBuilder sb = new StringBuilder(); converter.format(event, sb); final String result = sb.toString(); assertTrue("No suffix", result.contains("test suffix")); }
@Test public void testReplacement() { ThreadContext.put("MyKey", "Apache"); final LogEvent event = new Log4jLogEvent(RegexReplacementConverterTest.class.getName(), null, null, Level.DEBUG, new SimpleMessage("This is a test"), null); final StringBuilder sb = new StringBuilder(); final LoggerContext ctx = (LoggerContext) LogManager.getContext(); final String[] options = new String[] { "%logger %msg%n", "\\.", "/" }; final RegexReplacementConverter converter = RegexReplacementConverter.newInstance(ctx.getConfiguration(), options); converter.format(event, sb); assertEquals("org/apache/logging/log4j/core/pattern/RegexReplacementConverterTest This is a test" + Constants.LINE_SEP, sb.toString()); }
/** * Test the custom pattern */ @Test public void testCustomPattern() { final List<PatternFormatter> formatters = parser.parse(customPattern); assertNotNull(formatters); final Map<String, String> mdc = new HashMap<String, String>(); mdc.put("loginId", "Fred"); final Throwable t = new Throwable(); final StackTraceElement[] elements = t.getStackTrace(); final LogEvent event = new Log4jLogEvent("org.apache.logging.log4j.PatternParserTest", MarkerManager.getMarker("TEST"), Logger.class.getName(), Level.INFO, new SimpleMessage("Hello, world"), null, mdc, null, "Thread1", elements[0], System.currentTimeMillis()); final StringBuilder buf = new StringBuilder(); for (final PatternFormatter formatter : formatters) { formatter.format(event, buf); } final String str = buf.toString(); final String expected = "INFO [PatternParserTest :96 ] - Hello, world" + Constants.LINE_SEP; assertTrue("Expected to end with: " + expected + ". Actual: " + str, str.endsWith(expected)); }
@Test public void testNestedPattern() { final List<PatternFormatter> formatters = parser.parse(nestedPattern); assertNotNull(formatters); final Throwable t = new Throwable(); final StackTraceElement[] elements = t.getStackTrace(); final LogEvent event = new Log4jLogEvent("org.apache.logging.log4j.PatternParserTest", MarkerManager.getMarker("TEST"), Logger.class.getName(), Level.INFO, new SimpleMessage("Hello, world"), null, null, null, "Thread1", elements[0], System.currentTimeMillis()); final StringBuilder buf = new StringBuilder(); for (final PatternFormatter formatter : formatters) { formatter.format(event, buf); } final String str = buf.toString(); final String expected = String.format("] INFO : Hello, world%s\u001B[m", Constants.LINE_SEP); assertTrue(" Expected to end with: " + expected + ". Actual: " + str, str.endsWith(expected)); }
@Test public void testSuffix() { final String suffix = "suffix(test suffix)"; final String[] options = {suffix}; final ExtendedThrowablePatternConverter converter = ExtendedThrowablePatternConverter.newInstance(null, options); final Throwable cause = new NullPointerException("null pointer"); final Throwable parent = new IllegalArgumentException("IllegalArgument", cause); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("testLogger") // .setLoggerFqcn(this.getClass().getName()) // .setLevel(Level.DEBUG) // .setMessage(new SimpleMessage("test exception")) // .setThrown(parent).build(); final StringBuilder sb = new StringBuilder(); converter.format(event, sb); final String result = sb.toString(); assertTrue("No suffix", result.contains("test suffix")); }
@Test public void testConverter() { final MapMessage msg = new MapMessage(); msg.put("subject", "I"); msg.put("verb", "love"); msg.put("object", "Log4j"); final MapPatternConverter converter = MapPatternConverter.newInstance(null); final LogEvent event = new Log4jLogEvent("MyLogger", null, null, Level.DEBUG, msg, null); final StringBuilder sb = new StringBuilder(); converter.format(event, sb); final String str = sb.toString(); String expected = "subject=I"; assertTrue("Missing or incorrect subject. Expected " + expected + ", actual " + str, str.contains(expected)); expected = "verb=love"; assertTrue("Missing or incorrect verb", str.contains(expected)); expected = "object=Log4j"; assertTrue("Missing or incorrect object", str.contains(expected)); }
@Test public void testSuffixWillIgnoreThrowablePattern() { final String suffix = "suffix(%xEx{suffix(inner suffix)})"; final String[] options = {suffix}; final RootThrowablePatternConverter converter = RootThrowablePatternConverter.newInstance(null, options); final Throwable cause = new NullPointerException("null pointer"); final Throwable parent = new IllegalArgumentException("IllegalArgument", cause); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("testLogger") // .setLoggerFqcn(this.getClass().getName()) // .setLevel(Level.DEBUG) // .setMessage(new SimpleMessage("test exception")) // .setThrown(parent).build(); final StringBuilder sb = new StringBuilder(); converter.format(event, sb); final String result = sb.toString(); assertFalse("Has unexpected suffix", result.contains("inner suffix")); }
@Test public void testFull() { final ExtendedThrowablePatternConverter converter = ExtendedThrowablePatternConverter.newInstance(null); final Throwable cause = new NullPointerException("null pointer"); final Throwable parent = new IllegalArgumentException("IllegalArgument", cause); final LogEvent event = new Log4jLogEvent("testLogger", null, this.getClass().getName(), Level.DEBUG, new SimpleMessage("test exception"), parent); final StringBuilder sb = new StringBuilder(); converter.format(event, sb); final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw); parent.printStackTrace(pw); String result = sb.toString(); result = result.replaceAll(" ~?\\[.*\\]", ""); final String expected = sw.toString().replaceAll("\r", ""); assertEquals(expected, result); }
@Override public void run() { try { try (final Socket socket = serverSocket.accept()) { if (socket != null) { final InputStream is = socket.getInputStream(); while (!shutdown) { final MappingIterator<LogEvent> mappingIterator = objectMapper.readerFor(Log4jLogEvent.class).readValues(is); while (mappingIterator.hasNextValue()) { queue.add(mappingIterator.nextValue()); ++count; } } } } } catch (final EOFException eof) { // Socket is closed. } catch (final Exception e) { if (!shutdown) { Throwables.rethrow(e); } } }
@Test public void testFull1() { final RootThrowablePatternConverter converter = RootThrowablePatternConverter.newInstance(null, null); final Throwable cause = new NullPointerException("null pointer"); final Throwable parent = new IllegalArgumentException("IllegalArgument", cause); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("testLogger") // .setLoggerFqcn(this.getClass().getName()) // .setLevel(Level.DEBUG) // .setMessage(new SimpleMessage("test exception")) // .setThrown(parent).build(); final StringBuilder sb = new StringBuilder(); converter.format(event, sb); final String result = sb.toString(); // System.out.print(result); assertTrue("Missing Exception", result.contains("Wrapped by: java.lang.IllegalArgumentException: IllegalArgument")); assertTrue("Incorrect start of msg", result.startsWith("java.lang.NullPointerException: null pointer")); }
@Test public void testDisabledLookup() { final Configuration config = new DefaultConfigurationBuilder() .addProperty("foo", "bar") .build(true); final MessagePatternConverter converter = MessagePatternConverter.newInstance( config, new String[] {"nolookups"}); final Message msg = new ParameterizedMessage("${foo}"); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("MyLogger") // .setLevel(Level.DEBUG) // .setMessage(msg).build(); final StringBuilder sb = new StringBuilder(); converter.format(event, sb); assertEquals("Expected the raw pattern string without lookup", "${foo}", sb.toString()); }
@Test public void testShortMessage() { final String[] options = { "short.message" }; final ThrowablePatternConverter converter = ThrowablePatternConverter.newInstance(null, options); final Throwable cause = new NullPointerException("null pointer"); final Throwable parent = new IllegalArgumentException("IllegalArgument", cause); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("testLogger") // .setLoggerFqcn(this.getClass().getName()) // .setLevel(Level.DEBUG) // .setMessage(new SimpleMessage("test exception")) // .setThrown(parent).build(); final StringBuilder sb = new StringBuilder(); converter.format(event, sb); final String result = sb.toString(); assertEquals("The messages should be same", "IllegalArgument", result); }
private void compareLogEvents(final LogEvent orig, final LogEvent changed) { // Ensure that everything but the Mapped Data is still the same Assert.assertEquals("LoggerName changed", orig.getLoggerName(), changed.getLoggerName()); Assert.assertEquals("Marker changed", orig.getMarker(), changed.getMarker()); Assert.assertEquals("FQCN changed", orig.getFQCN(), changed.getFQCN()); Assert.assertEquals("Level changed", orig.getLevel(), changed.getLevel()); Assert.assertEquals("Throwable changed", orig.getThrown() == null // ? null // : ((Log4jLogEvent) orig).getThrownProxy().getExtendedStackTrace(), // changed.getThrown() == null // ? null // : ((Log4jLogEvent) changed).getThrownProxy().getExtendedStackTrace()); Assert.assertEquals("ContextMap changed", orig.getContextMap(), changed.getContextMap()); Assert.assertEquals("ContextStack changed", orig.getContextStack(), changed.getContextStack()); Assert.assertEquals("ThreadName changed", orig.getThreadName(), changed.getThreadName()); Assert.assertEquals("Source changed", orig.getSource(), changed.getSource()); Assert.assertEquals("Millis changed", orig.getMillis(), changed.getMillis()); }
@Test public void testUnixTimeMillis() throws Exception { final PatternLayout layout = PatternLayout.newBuilder().withPattern("%d{UNIX_MILLIS} %m") .withConfiguration(ctx.getConfiguration()).build(); final LogEvent event1 = Log4jLogEvent.newBuilder() // .setLoggerName(this.getClass().getName()).setLoggerFqcn("org.apache.logging.log4j.core.Logger") // .setLevel(Level.INFO) // .setMessage(new SimpleMessage("Hello, world 1!")).build(); final byte[] result1 = layout.toByteArray(event1); assertEquals(event1.getTimeMillis() + " Hello, world 1!", new String(result1)); // System.out.println("event1=" + event1.getTimeMillis()); final LogEvent event2 = Log4jLogEvent.newBuilder() // .setLoggerName(this.getClass().getName()).setLoggerFqcn("org.apache.logging.log4j.core.Logger") // .setLevel(Level.INFO) // .setMessage(new SimpleMessage("Hello, world 2!")).build(); final byte[] result2 = layout.toByteArray(event2); assertEquals(event2.getTimeMillis() + " Hello, world 2!", new String(result2)); // System.out.println("event2=" + event2.getTimeMillis()); }
private static void writer(final boolean lock, final int count, final String name) throws Exception { final Layout<String> layout = PatternLayout.createLayout(PatternLayout.SIMPLE_CONVERSION_PATTERN, null, null, null, null); final FileAppender app = FileAppender.createAppender(FILENAME, "true", Boolean.toString(lock), "test", "false", "false", "false", layout, null, "false", null, null); final Thread t = Thread.currentThread(); app.start(); assertTrue("Appender did not start", app.isStarted()); for (int i=0; i < count; ++i) { final LogEvent event = new Log4jLogEvent("TestLogger", null, FileAppenderTest.class.getName(), Level.INFO, new SimpleMessage("Test"), null, null, null, name, null, System.currentTimeMillis()); try { app.append(event); t.sleep(25); // Give up control long enough for another thread/process to occasionally do something. } catch (final Exception ex) { throw ex; } } app.stop(); assertFalse("Appender did not stop", app.isStarted()); }
@Test public void testLayoutLoggerName() throws Exception { final AbstractJacksonLayout layout = YamlLayout.newBuilder() .setLocationInfo(false) .setProperties(false) .setIncludeStacktrace(true) .setCharset(StandardCharsets.UTF_8) .build(); final Log4jLogEvent expected = Log4jLogEvent.newBuilder() // .setLoggerName("a.B") // .setLoggerFqcn("f.q.c.n") // .setLevel(Level.DEBUG) // .setMessage(new SimpleMessage("M")) // .setThreadName("threadName") // .setTimeMillis(1).build(); final String str = layout.toSerializable(expected); assertTrue(str, str.contains("loggerName: \"a.B\"")); final Log4jLogEvent actual = new Log4jYamlObjectMapper(false, true, false).readValue(str, Log4jLogEvent.class); assertEquals(expected.getLoggerName(), actual.getLoggerName()); assertEquals(expected, actual); }
private static LogEvent createLogEvent() { final Marker marker = null; final String fqcn = "com.mycom.myproject.mypackage.MyClass"; final Level level = Level.DEBUG; final Message message = new SimpleMessage(MESSAGE); final Throwable t = null; final StringMap mdc = null; final ThreadContext.ContextStack ndc = null; final String threadName = "THREAD"; final StackTraceElement location = null; final long timestamp = System.currentTimeMillis(); 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(); }
private static LogEvent createLogEvent() { final Marker marker = null; final String fqcn = "com.mycom.myproject.mypackage.MyClass"; final Level level = Level.DEBUG; final Message message = new SimpleMessage(STR); final Throwable t = null; final StringMap mdc = null; final 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(); }
@Test public void testShortOptionWithSuffix() { final String packageName = "org.apache.logging.log4j.core.pattern."; final String[] options = { "short.className", "suffix(test suffix)" }; final ThrowablePatternConverter converter = ThrowablePatternConverter.newInstance(null, options); final Throwable cause = new NullPointerException("null pointer"); final Throwable parent = new IllegalArgumentException("IllegalArgument", cause); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("testLogger") // .setLoggerFqcn(this.getClass().getName()) // .setLevel(Level.DEBUG) // .setMessage(new SimpleMessage("test exception")) // .setThrown(parent).build(); final StringBuilder sb = new StringBuilder(); converter.format(event, sb); final String result = sb.toString(); assertTrue("Each line should end with suffix", everyLineEndsWith(result, "test suffix")); }
private String prepareJSONForObjectMessageAsJsonObjectTests(final int value, final boolean objectMessageAsJsonObject) { final TestClass testClass = new TestClass(); testClass.setValue(value); // @formatter:off final Log4jLogEvent expected = Log4jLogEvent.newBuilder() .setLoggerName("a.B") .setLoggerFqcn("f.q.c.n") .setLevel(Level.DEBUG) .setMessage(new ObjectMessage(testClass)) .setThreadName("threadName") .setTimeMillis(1).build(); // @formatter:off final AbstractJacksonLayout layout = JsonLayout.newBuilder() .setCompact(true) .setObjectMessageAsJsonObject(objectMessageAsJsonObject) .build(); // @formatter:off return layout.toSerializable(expected); }
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(); }
@Test public void testFilter() { ThreadContext.put("userid", "testuser"); ThreadContext.put("organization", "apache"); final KeyValuePair[] pairs = new KeyValuePair[] { new KeyValuePair("testuser", "DEBUG"), new KeyValuePair("JohnDoe", "warn") }; final DynamicThresholdFilter filter = DynamicThresholdFilter.createFilter("userid", pairs, Level.ERROR, null, null); filter.start(); assertTrue(filter.isStarted()); assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null)); assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.ERROR, null, (Object) null, (Throwable) null)); ThreadContext.clearMap(); ThreadContext.put("userid", "JohnDoe"); ThreadContext.put("organization", "apache"); LogEvent event = Log4jLogEvent.newBuilder().setLevel(Level.DEBUG).setMessage(new SimpleMessage("Test")).build(); assertSame(Filter.Result.DENY, filter.filter(event)); event = Log4jLogEvent.newBuilder().setLevel(Level.ERROR).setMessage(new SimpleMessage("Test")).build(); assertSame(Filter.Result.NEUTRAL, filter.filter(event)); ThreadContext.clearMap(); }
@Test public void testShortFileName() { final String[] options = { "short.fileName" }; final ThrowablePatternConverter converter = ThrowablePatternConverter.newInstance(null, options); final Throwable cause = new NullPointerException("null pointer"); final Throwable parent = new IllegalArgumentException("IllegalArgument", cause); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("testLogger") // .setLoggerFqcn(this.getClass().getName()) // .setLevel(Level.DEBUG) // .setMessage(new SimpleMessage("test exception")) // .setThrown(parent).build(); final StringBuilder sb = new StringBuilder(); converter.format(event, sb); final String result = sb.toString(); assertEquals("The file names should be same", "ThrowablePatternConverterTest.java", result); }
@Test public void testLayoutLoggerName() { final XmlLayout layout = XmlLayout.newBuilder() .setLocationInfo(false) .setProperties(true) .setComplete(true) .setCompact(false) .setIncludeStacktrace(true) .build(); final Log4jLogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("a.B") // .setLoggerFqcn("f.q.c.n") // .setLevel(Level.DEBUG) // .setMessage(new SimpleMessage("M")) // .setThreadName("threadName") // .setTimeMillis(1).build(); final String str = layout.toSerializable(event); assertTrue(str, str.contains("loggerName=\"a.B\"")); }
@Test public void testSuffixWillIgnoreThrowablePattern() { final String suffix = "suffix(%xEx{suffix(inner suffix)})"; final String[] options = {suffix}; final ExtendedThrowablePatternConverter converter = ExtendedThrowablePatternConverter.newInstance(null, options); final Throwable cause = new NullPointerException("null pointer"); final Throwable parent = new IllegalArgumentException("IllegalArgument", cause); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("testLogger") // .setLoggerFqcn(this.getClass().getName()) // .setLevel(Level.DEBUG) // .setMessage(new SimpleMessage("test exception")) // .setThrown(parent).build(); final StringBuilder sb = new StringBuilder(); converter.format(event, sb); final String result = sb.toString(); assertFalse("Has unexpected suffix", result.contains("inner suffix")); }
@Test public void testConverterWithKey() { final StringMapMessage msg = new StringMapMessage(); msg.put("subject", "I"); msg.put("verb", "love"); msg.put("object", "Log4j"); final MapPatternConverter converter = MapPatternConverter.newInstance(new String[] {"object"}); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("MyLogger") // .setLevel(Level.DEBUG) // .setMessage(msg) // .build(); final StringBuilder sb = new StringBuilder(); converter.format(event, sb); final String str = sb.toString(); final String expected = "Log4j"; assertEquals(expected, str); }
@Test public void testPatternSelector() throws Exception { final PatternMatch[] patterns = new PatternMatch[1]; patterns[0] = new PatternMatch("FLOW", "%d %-5p [%t]: ====== %C{1}.%M:%L %m ======%n"); final PatternSelector selector = MarkerPatternSelector.createSelector(patterns, "%d %-5p [%t]: %m%n", true, true, ctx.getConfiguration()); final PatternLayout layout = PatternLayout.newBuilder().withPatternSelector(selector) .withConfiguration(ctx.getConfiguration()).build(); final LogEvent event1 = Log4jLogEvent.newBuilder() // .setLoggerName(this.getClass().getName()).setLoggerFqcn("org.apache.logging.log4j.core.layout.PatternSelectorTest$FauxLogger") .setMarker(MarkerManager.getMarker("FLOW")) .setLevel(Level.TRACE) // .setIncludeLocation(true) .setMessage(new SimpleMessage("entry")).build(); final String result1 = new FauxLogger().formatEvent(event1, layout); final String expectSuffix1 = String.format("====== PatternSelectorTest.testPatternSelector:53 entry ======%n"); assertTrue("Unexpected result: " + result1, result1.endsWith(expectSuffix1)); final LogEvent event2 = Log4jLogEvent.newBuilder() // .setLoggerName(this.getClass().getName()).setLoggerFqcn("org.apache.logging.log4j.core.Logger") // .setLevel(Level.INFO) // .setMessage(new SimpleMessage("Hello, world 1!")).build(); final String result2 = new String(layout.toByteArray(event2)); final String expectSuffix2 = String.format("Hello, world 1!%n"); assertTrue("Unexpected result: " + result2, result2.endsWith(expectSuffix2)); }
/** * Actual writing occurs here. * * @param logEvent The LogEvent. */ @Override public void append(final LogEvent logEvent) { if (!isStarted()) { throw new IllegalStateException("AsyncAppender " + getName() + " is not active"); } final Log4jLogEvent memento = Log4jLogEvent.createMemento(logEvent, includeLocation); InternalAsyncUtil.makeMessageImmutable(logEvent.getMessage()); if (!transfer(memento)) { if (blocking) { if (AbstractLogger.getRecursionDepth() > 1) { // LOG4J2-1518, LOG4J2-2031 // If queue is full AND we are in a recursive call, call appender directly to prevent deadlock final Message message = AsyncQueueFullMessageUtil.transform(logEvent.getMessage()); logMessageInCurrentThread(new Log4jLogEvent.Builder(logEvent).setMessage(message).build()); } else { // delegate to the event router (which may discard, enqueue and block, or log in current thread) final EventRoute route = asyncQueueFullPolicy.getRoute(thread.getId(), memento.getLevel()); route.logMessage(this, memento); } } else { error("Appender " + getName() + " is unable to write primary appenders. queue is full"); logToErrorAppenderIfNecessary(false, memento); } } }
private LogEvent prepareEvent(final LogEvent event) { LogEvent logEvent = ensureImmutable(event); if (logEvent.getMessage() instanceof ReusableMessage) { if (logEvent instanceof Log4jLogEvent) { ((Log4jLogEvent) logEvent).makeMessageImmutable(); } else if (logEvent instanceof MutableLogEvent) { // MutableLogEvents need to be translated into the RingBuffer by the MUTABLE_TRANSLATOR. // That translator calls MutableLogEvent.initFrom to copy the event, which will makeMessageImmutable the message. if (translator != MUTABLE_TRANSLATOR) { // should not happen... // TRANSLATOR expects an immutable LogEvent logEvent = ((MutableLogEvent) logEvent).createMemento(); } } else { // custom log event, with a ReusableMessage showWarningAboutCustomLogEventWithReusableMessage(logEvent); } } else { // message is not a ReusableMessage; makeMessageImmutable it to prevent ConcurrentModificationExceptions InternalAsyncUtil.makeMessageImmutable(logEvent.getMessage()); // LOG4J2-1988, LOG4J2-1914 } return logEvent; }
@Test public void testShortLocalizedMessage() { final String[] options = { "short.localizedMessage" }; final ThrowablePatternConverter converter = ThrowablePatternConverter.newInstance(null, options); final Throwable parent = new LocalizedException(); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("testLogger") // .setLoggerFqcn(this.getClass().getName()) // .setLevel(Level.DEBUG) // .setMessage(new SimpleMessage("test exception")) // .setThrown(parent).build(); final StringBuilder sb = new StringBuilder(); converter.format(event, sb); final String result = sb.toString(); assertEquals("The messages should be same", "I am localized.", result); }
ObjectWriter newWriter(final boolean locationInfo, final boolean properties, final boolean compact) { final SimpleFilterProvider filters = new SimpleFilterProvider(); final Set<String> except = new HashSet<>(2); if (!locationInfo) { except.add(this.getPropertNameForSource()); } if (!properties) { except.add(this.getPropertNameForContextMap()); } except.add(this.getPropertNameForNanoTime()); filters.addFilter(Log4jLogEvent.class.getName(), SimpleBeanPropertyFilter.serializeAllExcept(except)); final ObjectWriter writer = this.newObjectMapper().writer(compact ? this.newCompactPrinter() : this.newPrettyPrinter()); return writer.with(filters); }
@Test public void testShortClassName() { final String packageName = "org.apache.logging.log4j.core.pattern."; final String[] options = { "short.className" }; final ThrowablePatternConverter converter = ThrowablePatternConverter.newInstance(null, options); final Throwable cause = new NullPointerException("null pointer"); final Throwable parent = new IllegalArgumentException("IllegalArgument", cause); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("testLogger") // .setLoggerFqcn(this.getClass().getName()) // .setLevel(Level.DEBUG) // .setMessage(new SimpleMessage("test exception")) // .setThrown(parent).build(); final StringBuilder sb = new StringBuilder(); converter.format(event, sb); final String result = sb.toString(); assertEquals("The class names should be same", packageName + "ThrowablePatternConverterTest", result); }