org.apache.logging.log4j.message.SimpleMessage Java Examples

The following examples show how to use org.apache.logging.log4j.message.SimpleMessage. 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: EncodingPatternConverterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCrlfEscaping() {
    final LogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName(EncodingPatternConverterTest.class.getName()) //
            .setLevel(Level.DEBUG) //
            .setMessage(new SimpleMessage("Test \r\n<div class=\"test\">this\r</div> & \n<div class='test'>that</div>"))
            .build();
    final StringBuilder sb = new StringBuilder();
    final LoggerContext ctx = LoggerContext.getContext();
    final String[] options = new String[]{"%msg", "CRLF"};
    final EncodingPatternConverter converter = EncodingPatternConverter
        .newInstance(ctx.getConfiguration(), options);
    assertNotNull("Error creating converter", converter);
    converter.format(event, sb);
    assertEquals(
        "Test \\r\\n<div class=\"test\">this\\r</div> & \\n<div class='test'>that</div>",
        sb.toString());
}
 
Example #2
Source File: RegexReplacementConverterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testReplacement() {
    ThreadContext.put("MyKey", "Apache");
    final LogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName(RegexReplacementConverterTest.class.getName()) //
            .setLevel(Level.DEBUG) //
            .setMessage(new SimpleMessage("This is a test")) //
            .build();
    final StringBuilder sb = new StringBuilder();
    final LoggerContext ctx = LoggerContext.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" +
        Strings.LINE_SEPARATOR, sb.toString());
}
 
Example #3
Source File: LevelPatternConverterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testLevelLowerCase() {
    final Message msg = new SimpleMessage("Hello");
    LogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName("MyLogger") //
            .setLevel(Level.DEBUG) //
            .setMessage(msg).build();
    final StringBuilder sb = new StringBuilder();
    LevelPatternConverter converter = LevelPatternConverter.newInstance(null);
    converter.format(event, sb);
    assertEquals(Level.DEBUG.toString(), sb.toString());
    final String[] opts = new String[] { "lowerCase=true" };
    converter = LevelPatternConverter.newInstance(opts);
    sb.setLength(0);
    converter.format(event, sb);
    assertEquals("debug", sb.toString());
    event = Log4jLogEvent.newBuilder() //
            .setLoggerName("MyLogger") //
            .setLevel(Level.WARN) //
            .setMessage(msg).build();
    sb.setLength(0);
    converter.format(event, sb);
    assertEquals("warn", sb.toString());
}
 
Example #4
Source File: JsonTemplateLayoutTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void test_lineSeparator_suffix() {

    // Create the log event.
    final SimpleMessage message = new SimpleMessage("Hello, World!");
    final LogEvent logEvent = Log4jLogEvent
            .newBuilder()
            .setLoggerName(LOGGER_NAME)
            .setLevel(Level.INFO)
            .setMessage(message)
            .build();

    // Check line separators.
    test_lineSeparator_suffix(logEvent, true);
    test_lineSeparator_suffix(logEvent, false);

}
 
Example #5
Source File: TestLoggingEventStringSerde.java    From samza with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
  String testLog = "testing";
  Logger logger = (Logger) LogManager.getLogger(TestLoggingEventStringSerde.class);
  LogEvent log = Log4jLogEvent.newBuilder()
      .setLevel(logger.getLevel())
      .setLoggerName(logger.getName())
      .setMessage(new SimpleMessage(testLog))
      .setThrown(null)
      .build();
  LoggingEventStringSerde loggingEventStringSerde = new LoggingEventStringSerde();

  assertNull(loggingEventStringSerde.fromBytes(null));
  assertNull(loggingEventStringSerde.toBytes(null));

  assertArrayEquals(testLog.getBytes(), loggingEventStringSerde.toBytes(log));
  // only the log messages are guaranteed to be equivalent
  assertEquals(log.getMessage().toString(), loggingEventStringSerde.fromBytes(testLog.getBytes()).getMessage().toString());
}
 
Example #6
Source File: RootThrowablePatternConverterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@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"));
}
 
Example #7
Source File: ExtendedThrowablePatternConverterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testFull() {
    final ExtendedThrowablePatternConverter converter = ExtendedThrowablePatternConverter.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 StringWriter sw = new StringWriter();
    final PrintWriter pw = new PrintWriter(sw);
    parent.printStackTrace(pw);
    String result = sb.toString();
    result = result.replaceAll(" ~?\\[.*\\]", Strings.EMPTY);
    final String expected = sw.toString(); //.replaceAll("\r", Strings.EMPTY);
    assertEquals(expected, result);
}
 
Example #8
Source File: ThrowablePatternConverterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@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"));
}
 
Example #9
Source File: RegexFilterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #10
Source File: PatternParserTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private void testNestedPatternHighlight(final Level level, final String expectedStart) {
    final List<PatternFormatter> formatters = parser.parse(nestedPatternHighlight);
    assertNotNull(formatters);
    final Throwable t = new Throwable();
    t.getStackTrace();
    final LogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName("org.apache.logging.log4j.PatternParserTest") //
            .setMarker(MarkerManager.getMarker("TEST")) //
            .setLoggerFqcn(Logger.class.getName()) //
            .setLevel(level) //
            .setMessage(new SimpleMessage("Hello, world")) //
            .setThreadName("Thread1") //
            .setSource(/*stackTraceElement[0]*/ null) //
            .setTimeMillis(System.currentTimeMillis()) //
            .build();
    final StringBuilder buf = new StringBuilder();
    for (final PatternFormatter formatter : formatters) {
        formatter.format(event, buf);
    }
    final String str = buf.toString();
    final String expectedEnd = String.format("] %-5s: Hello, world%s\u001B[m", level, Strings.LINE_SEPARATOR);
    assertTrue("Expected to start with: " + expectedStart + ". Actual: " + str, str.startsWith(expectedStart));
    assertTrue("Expected to end with: \"" + expectedEnd + "\". Actual: \"" + str, str.endsWith(expectedEnd));
}
 
Example #11
Source File: YamlLayoutTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@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);
    assertThat(str, containsString("loggerName: \"a.B\""));
    final Log4jLogEvent actual = new Log4jYamlObjectMapper(false, true, false).readValue(str, Log4jLogEvent.class);
    assertEquals(expected.getLoggerName(), actual.getLoggerName());
    assertEquals(expected, actual);
}
 
Example #12
Source File: MdcPatternConverterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testConverterFullEmpty() {
    ThreadContext.clearMap();
    final Message msg = new SimpleMessage("Hello");
    final MdcPatternConverter converter = MdcPatternConverter.newInstance(null);
    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 = "{}";
    assertTrue("Incorrect result. Expected " + expected + ", actual " + str, str.equals(expected));
}
 
Example #13
Source File: MdcPatternConverterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testConverterWithKey() {
    final Message msg = new SimpleMessage("Hello");
    final String [] options = new String[] {"object"};
    final MdcPatternConverter converter = MdcPatternConverter.newInstance(options);
    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);
}
 
Example #14
Source File: PatternLayoutComparisonBenchmark.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private static LogEvent createLog4j2Event() {
    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();
}
 
Example #15
Source File: MessageResolver.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private static EventResolver createObjectResolver(final String fallbackKey) {
    return (final LogEvent logEvent, final JsonWriter jsonWriter) -> {

        // Skip custom serializers for SimpleMessage.
        final Message message = logEvent.getMessage();
        final boolean simple = message instanceof SimpleMessage;
        if (!simple) {

            // Try MultiformatMessage serializer.
            if (writeMultiformatMessage(jsonWriter, message)) {
                return;
            }

            // Try ObjectMessage serializer.
            if (writeObjectMessage(jsonWriter, message)) {
                return;
            }

        }

        // Fallback to plain String serializer.
        resolveString(fallbackKey, logEvent, jsonWriter);

    };
}
 
Example #16
Source File: ExtendedThrowablePatternConverterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testFiltering() {
    final String packages = "filters(org.junit, org.apache.maven, sun.reflect, java.lang.reflect)";
    final String[] options = {packages};
    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 suppressed lines", result.contains(" suppressed "));
}
 
Example #17
Source File: ThresholdFilterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testThresholds() {
    final ThresholdFilter filter = ThresholdFilter.createFilter(Level.ERROR, null, null);
    filter.start();
    assertTrue(filter.isStarted());
    assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null));
    assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.ERROR, null, (Object) null, (Throwable) null));
    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));
}
 
Example #18
Source File: TextEncoderHelperBenchmark.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #19
Source File: ConsoleAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private void testConsoleStreamManagerDoesNotClose(final PrintStream ps, final Target targetName, final SystemSetter systemSetter) {
    try {
        systemSetter.systemSet(psMock);
        final Layout<String> layout = PatternLayout.newBuilder().setAlwaysWriteExceptions(true).build();
        final ConsoleAppender app = ConsoleAppender.newBuilder().setLayout(layout).setTarget(targetName)
                .setName("Console").setIgnoreExceptions(false).build();
        app.start();
        assertTrue("Appender did not start", app.isStarted());

        final LogEvent event = Log4jLogEvent.newBuilder() //
                .setLoggerName("TestLogger") //
                .setLoggerFqcn(ConsoleAppenderTest.class.getName()) //
                .setLevel(Level.INFO) //
                .setMessage(new SimpleMessage("Test")) //
                .build();
        app.append(event);

        app.stop();
        assertFalse("Appender did not stop", app.isStarted());
    } finally {
        systemSetter.systemSet(ps);
    }
    then(psMock).should(atLeastOnce()).write(any(byte[].class), anyInt(), anyInt());
    then(psMock).should(atLeastOnce()).flush();
}
 
Example #20
Source File: ThrowablePatternConverterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #21
Source File: Log4j1XmlLayoutTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithoutThrown() {
    final Log4j1XmlLayout layout = Log4j1XmlLayout.createLayout(false, true);

    final Log4jLogEvent event = Log4jLogEvent.newBuilder()
            .setLoggerName("a.B")
            .setLevel(Level.INFO)
            .setMessage(new SimpleMessage("Hello, World"))
            .setTimeMillis(System.currentTimeMillis() + 17)
            .build();

    final String result = layout.toSerializable(event);

    final String expected =
            "<log4j:event logger=\"a.B\" timestamp=\"" + event.getTimeMillis() + "\" level=\"INFO\" thread=\"main\">\r\n" +
            "<log4j:message><![CDATA[Hello, World]]></log4j:message>\r\n" +
            "</log4j:event>\r\n\r\n";

    assertEquals(expected, result);
}
 
Example #22
Source File: AbstractLogger.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
protected EntryMessage entryMsg(final String format, final Object... params) {
    final int count = params == null ? 0 : params.length;
    if (count == 0) {
        if (Strings.isEmpty(format)) {
            return flowMessageFactory.newEntryMessage(null);
        }
        return flowMessageFactory.newEntryMessage(new SimpleMessage(format));
    }
    if (format != null) {
        return flowMessageFactory.newEntryMessage(new ParameterizedMessage(format, params));
    }
    final StringBuilder sb = new StringBuilder();
    sb.append("params(");
    for (int i = 0; i < count; i++) {
        if (i > 0) {
            sb.append(", ");
        }
        final Object parm = params[i];
        sb.append(parm instanceof Message ? ((Message) parm).getFormattedMessage() : String.valueOf(parm));
    }
    sb.append(')');
    return flowMessageFactory.newEntryMessage(new SimpleMessage(sb));
}
 
Example #23
Source File: LevelPatternConverterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testLevelMap() {
    final Message msg = new SimpleMessage("Hello");
    LogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName("MyLogger") //
            .setLevel(Level.DEBUG) //
            .setMessage(msg).build();
    final StringBuilder sb = new StringBuilder();
    LevelPatternConverter converter = LevelPatternConverter.newInstance(null);
    converter.format(event, sb);
    assertEquals(Level.DEBUG.toString(), sb.toString());
    final String[] opts = new String[] { "WARN=Warning, DEBUG=Debug, ERROR=Error, TRACE=Trace, INFO=Info" };
    converter = LevelPatternConverter.newInstance(opts);
    sb.setLength(0);
    converter.format(event, sb);
    assertEquals("Debug", sb.toString());
    event = Log4jLogEvent.newBuilder() //
            .setLoggerName("MyLogger") //
            .setLevel(Level.WARN) //
            .setMessage(msg).build();
    sb.setLength(0);
    converter.format(event, sb);
    assertEquals("Warning", sb.toString());
}
 
Example #24
Source File: ExtendedThrowablePatternConverterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@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"));
}
 
Example #25
Source File: ThrowablePatternConverterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #26
Source File: PatternLayoutTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnixTimeMillis() throws Exception {
    final PatternLayout layout = PatternLayout.newBuilder().setPattern("%d{UNIX_MILLIS} %m")
            .setConfiguration(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());
}
 
Example #27
Source File: PatternLayoutTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testRegexEmptyMarker() throws Exception {
    // replace "[]" with the empty string
    final PatternLayout layout = PatternLayout.newBuilder().setPattern("[%logger]%replace{[%marker]}{\\[\\]}{} %msg")
            .setConfiguration(ctx.getConfiguration()).build();
    // Not empty marker
    final LogEvent event1 = Log4jLogEvent.newBuilder() //
            .setLoggerName(this.getClass().getName()).setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
            .setLevel(Level.INFO) //
            .setMarker(MarkerManager.getMarker("TestMarker")) //
            .setMessage(new SimpleMessage("Hello, world!")).build();
    assertToByteArray("[org.apache.logging.log4j.core.layout.PatternLayoutTest][TestMarker] Hello, world!", layout,
            event1);
    assertEncode("[org.apache.logging.log4j.core.layout.PatternLayoutTest][TestMarker] Hello, world!", layout,
            event1);

    // empty marker
    final LogEvent event2 = Log4jLogEvent.newBuilder() //
            .setLoggerName(this.getClass().getName()).setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
            .setLevel(Level.INFO) //
            .setMessage(new SimpleMessage("Hello, world!")).build();
    assertToByteArray("[org.apache.logging.log4j.core.layout.PatternLayoutTest] Hello, world!", layout, event2);
    assertEncode("[org.apache.logging.log4j.core.layout.PatternLayoutTest] Hello, world!", layout, event2);
}
 
Example #28
Source File: PatternParserTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testPatternTruncateFromBeginning() {
    final List<PatternFormatter> formatters = parser.parse(patternTruncateFromBeginning);
    assertNotNull(formatters);
    final LogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName("org.apache.logging.log4j.PatternParserTest") //
            .setLoggerFqcn(Logger.class.getName()) //
            .setLevel(Level.INFO) //
            .setMessage(new SimpleMessage("Hello, world")) //
            .setThreadName("Thread1") //
            .setTimeMillis(System.currentTimeMillis()) //
            .build();
    final StringBuilder buf = new StringBuilder();
    for (final PatternFormatter formatter : formatters) {
        formatter.format(event, buf);
    }
    final String str = buf.toString();
    final String expected = "INFO  rTest Hello, world" + Strings.LINE_SEPARATOR;
    assertTrue("Expected to end with: " + expected + ". Actual: " + str, str.endsWith(expected));
}
 
Example #29
Source File: PatternLayoutBenchmark.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #30
Source File: RingBufferLogEventTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSerializationDeserialization() throws IOException, ClassNotFoundException {
    final RingBufferLogEvent evt = new RingBufferLogEvent();
    final String loggerName = "logger.name";
    final Marker marker = null;
    final String fqcn = "f.q.c.n";
    final Level level = Level.TRACE;
    final Message data = new SimpleMessage("message");
    final Throwable t = new InternalError("not a real error");
    final ContextStack contextStack = null;
    final String threadName = "main";
    final StackTraceElement location = null;
    evt.setValues(null, loggerName, marker, fqcn, level, data, t, (StringMap) evt.getContextData(),
            contextStack, -1, threadName, -1, location,
            new FixedPreciseClock(12345, 678), new DummyNanoClock(1));
    ((StringMap) evt.getContextData()).putValue("key", "value");

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final ObjectOutputStream out = new ObjectOutputStream(baos);
    out.writeObject(evt);

    final ObjectInputStream in = new FilteredObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
    final RingBufferLogEvent other = (RingBufferLogEvent) in.readObject();
    assertEquals(loggerName, other.getLoggerName());
    assertEquals(marker, other.getMarker());
    assertEquals(fqcn, other.getLoggerFqcn());
    assertEquals(level, other.getLevel());
    assertEquals(data, other.getMessage());
    assertNull("null after serialization", other.getThrown());
    assertEquals(new ThrowableProxy(t), other.getThrownProxy());
    assertEquals(evt.getContextData(), other.getContextData());
    assertEquals(contextStack, other.getContextStack());
    assertEquals(threadName, other.getThreadName());
    assertEquals(location, other.getSource());
    assertEquals(12345, other.getTimeMillis());
    assertEquals(678, other.getInstant().getNanoOfMillisecond());
}