Java 类org.apache.logging.log4j.message.SimpleMessage 实例源码

项目:cas-5.1.0    文件:LoggingUtils.java   
/**
 * 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;
}
项目:log4j2-logstash-layout    文件:LogstashLayoutTest.java   
@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();

}
项目:graylog-plugin-internal-logs    文件:SerializedLogEventTransportTest.java   
@Test
public void launchCreatesAndStartsAppenderAndProcessesMessages() throws Exception {
    final MessageInput messageInput = mock(MessageInput.class);
    transport.launch(messageInput);

    final DirectConsumingAppender appender = transport.getAppender();
    assertThat(appender.getName()).isEqualTo("graylog-plugin-internal-logs");
    assertThat(appender.getLayout()).isInstanceOf(SerializedLayout.class);
    assertThat(appender.isStarted()).isTrue();

    final MutableLogEvent logEvent = new MutableLogEvent();
    logEvent.setMessage(new SimpleMessage("Processed"));
    logEvent.setLevel(Level.ERROR);
    appender.append(logEvent);
    verify(messageInput, times(1)).processRawMessage(any(RawMessage.class));

    final MutableLogEvent ignoredLogEvent = new MutableLogEvent();
    ignoredLogEvent.setMessage(new SimpleMessage("Ignored"));
    ignoredLogEvent.setLevel(Level.TRACE);
    appender.append(ignoredLogEvent);
    verifyNoMoreInteractions(messageInput);
}
项目:graylog-plugin-internal-logs    文件:SerializedLogEventCodecTest.java   
private LogEvent createLogEvent(DateTime timestamp) {
    final MutableLogEvent logEvent = new MutableLogEvent();

    logEvent.setMessage(new SimpleMessage("Test"));
    logEvent.setLevel(Level.TRACE);
    logEvent.setLoggerName("org.example.Test");
    logEvent.setMarker(MarkerManager.getMarker("TestMarker"));
    logEvent.setTimeMillis(timestamp.getMillis());
    logEvent.setNanoTime(42L);

    logEvent.setContextStack(new MutableThreadContextStack(ImmutableList.of("one", "two")));
    final SortedArrayStringMap contextData = new SortedArrayStringMap(1);
    contextData.putValue("foobar", "quux");
    logEvent.setContextData(contextData);

    logEvent.setThreadId(23L);
    logEvent.setThreadName("thread-name");
    logEvent.setThreadPriority(42);

    logEvent.setThrown(new Throwable("Test", new Throwable("cause")));

    logEvent.setIncludeLocation(true);

    return logEvent.createMemento();
}
项目:daikon    文件:Log4j2JSONLayoutTest.java   
@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();
}
项目:logging-log4j2    文件:ExtendedThrowablePatternConverterTest.java   
@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);
}
项目:logging-log4j2    文件:InMemoryAppenderTest.java   
private void assertMessage(final String string, final InMemoryAppender app, final String header) {
    final LogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName("TestLogger") //
            .setLoggerFqcn(InMemoryAppenderTest.class.getName()) //
            .setLevel(Level.INFO) //
            .setMessage(new SimpleMessage("Test")) //
            .build();
    app.start();
    assertTrue("Appender did not start", app.isStarted());
    app.append(event);
    app.append(event);
    final String msg = app.toString();
    assertNotNull("No message", msg);
    final String expectedHeader = header == null ? "" : header;
    final String expected = expectedHeader + "Test" + Strings.LINE_SEPARATOR + "Test" + Strings.LINE_SEPARATOR;
    assertTrue("Incorrect message: " + msg, msg.equals(expected));
    app.stop();
    assertFalse("Appender did not stop", app.isStarted());
}
项目:log4j2    文件:RegexReplacementConverterTest.java   
@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());
}
项目:log4j2    文件:PatternParserTest.java   
/**
 * 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));
}
项目:log4j2    文件:PatternParserTest.java   
@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));
}
项目:log4j2    文件:ExtendedThrowablePatternConverterTest.java   
@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);
}
项目:logging-log4j2    文件:ThresholdFilterTest.java   
@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));
}
项目:logging-log4j2    文件:EncodingPatternConverterTest.java   
@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());
}
项目:logging-log4j2    文件:PatternLayoutTest.java   
@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());
}
项目:logging-log4j2    文件:ThrowablePatternConverterTest.java   
@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);
}
项目:log4j2    文件:ConsoleAppenderTest.java   
@Test
public void testFollow() {
    final PrintStream ps = System.out;
    final Layout<String> layout = PatternLayout.createLayout(null, null, null, null, null);
    final ConsoleAppender app = ConsoleAppender.createAppender(layout, null, "SYSTEM_OUT", "Console", "true", "false");
    app.start();
    final LogEvent event = new Log4jLogEvent("TestLogger", null, ConsoleAppenderTest.class.getName(), Level.INFO,
        new SimpleMessage("Test"), null);

    assertTrue("Appender did not start", app.isStarted());
    System.setOut(new PrintStream(baos));
    app.append(event);
    System.setOut(ps);
    final String msg = baos.toString();
    assertNotNull("No message", msg);
    assertTrue("Incorrect message: " + msg , msg.endsWith("Test" + Constants.LINE_SEP));
    app.stop();
    assertFalse("Appender did not stop", app.isStarted());
}
项目:log4j2    文件:FileAppenderTest.java   
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());
}
项目:logging-log4j2    文件:PatternLayoutTest.java   
@SuppressWarnings("unused")
private void testUnixTime(final String pattern) throws Exception {
    final PatternLayout layout = PatternLayout.newBuilder().withPattern(pattern + " %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.getMillis());
    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.getMillis());
}
项目:logging-log4j2    文件:PatternLayoutBenchmark.java   
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();
}
项目:logging-log4j2    文件:AbstractStringLayoutStringEncodingBenchmark.java   
@Setup
public void setUp() {
    bytes = new byte[128];
    for (int i = 0; i<bytes.length; i++) {
        bytes[i] = (byte)i;
    }

    usAsciiGetBytesLayout = new GetBytesLayout(Charset.forName("US-ASCII"));
    iso8859_1GetBytesLayout = new GetBytesLayout(Charset.forName("ISO-8859-1"));
    utf8GetBytesLayout = new GetBytesLayout(Charset.forName("UTF-8"));
    utf16GetBytesLayout = new GetBytesLayout(Charset.forName("UTF-16"));

    usAsciiEncodeLayout = new EncodeLayout(Charset.forName("US-ASCII"));
    iso8859_1EncodeLayout = new EncodeLayout(Charset.forName("ISO-8859-1"));
    utf8EncodeLayout = new EncodeLayout(Charset.forName("UTF-8"));
    utf16EncodeLayout = new EncodeLayout(Charset.forName("UTF-16"));

    final StringBuilder msg = new StringBuilder();
    msg.append(MESSAGE);

    logEvent = createLogEvent(new SimpleMessage(msg));

    destination = new Destination();
}
项目:logging-log4j2    文件:GelfLayoutBenchmark.java   
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();
}
项目:logging-log4j2    文件:TextEncoderHelperBenchmark.java   
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();
}
项目:logging-log4j2    文件:RootThrowablePatternConverterTest.java   
@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"));
}
项目:logging-log4j2    文件:PatternLayoutTest.java   
@Test
public void testEqualsMarkerWithMessageSubstitution() throws Exception {
    // replace "[]" with the empty string
    final PatternLayout layout = PatternLayout.newBuilder().withPattern("[%logger]%equals{[%marker]}{[]}{[%msg]}")
        .withConfiguration(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();
    final byte[] result1 = layout.toByteArray(event1);
    assertEquals("[org.apache.logging.log4j.core.layout.PatternLayoutTest][TestMarker]", new String(result1));
    // 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();
    final byte[] result2 = layout.toByteArray(event2);
    assertEquals("[org.apache.logging.log4j.core.layout.PatternLayoutTest][Hello, world!]", new String(result2));
}
项目:logging-log4j2    文件:RegexFilterTest.java   
@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);
}
项目:logging-log4j2    文件:PatternLayoutTest.java   
@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.PatternLayoutTest$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 expectPattern1 = String.format(".*====== PatternLayoutTest.testPatternSelector:\\d+ entry ======%n");
    assertTrue("Unexpected result: " + result1, result1.matches(expectPattern1));
    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));
}
项目:logging-log4j2    文件:Log4j1XmlLayoutTest.java   
@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);
}
项目:logging-log4j2    文件:ThrowablePatternConverterTest.java   
@Test
public void testShortMethodName() {
    final String[] options = { "short.methodName" };
    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 method names should be same", "testShortMethodName", result);
}
项目:logging-log4j2    文件:ReusableLogEventFactoryTest.java   
@Test
public void testCreateEventOverwritesFields() throws Exception {
    final ReusableLogEventFactory factory = new ReusableLogEventFactory();
    final LogEvent event1 = callCreateEvent(factory, "a", Level.DEBUG, new SimpleMessage("abc"), null);
    assertEquals("logger", "a", event1.getLoggerName());
    assertEquals("level", Level.DEBUG, event1.getLevel());
    assertEquals("msg", new SimpleMessage("abc"), event1.getMessage());

    ReusableLogEventFactory.release(event1);
    final LogEvent event2 = callCreateEvent(factory, "b", Level.INFO, new SimpleMessage("xyz"), null);
    assertSame(event1, event2);

    assertEquals("logger", "b", event1.getLoggerName());
    assertEquals("level", Level.INFO, event1.getLevel());
    assertEquals("msg", new SimpleMessage("xyz"), event1.getMessage());
    assertEquals("logger", "b", event2.getLoggerName());
    assertEquals("level", Level.INFO, event2.getLevel());
    assertEquals("msg", new SimpleMessage("xyz"), event2.getMessage());
}
项目:logging-log4j2    文件:PatternLayoutTest.java   
@Test
public void testRegexEmptyMarker() throws Exception {
    // replace "[]" with the empty string
    final PatternLayout layout = PatternLayout.newBuilder().withPattern("[%logger]%replace{[%marker]}{\\[\\]}{} %msg")
            .withConfiguration(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);
}
项目:logging-log4j2    文件:MdcPatternConverterTest.java   
@Test
public void testConverterWithExistingData() {
    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();
    sb.append("prefix ");
    converter.format(event, sb);
    final String str = sb.toString();
    final String expected = "prefix {object=Log4j, subject=I, verb=love}";
    assertTrue("Incorrect result. Expected " + expected + ", actual " + str, str.equals(expected));
}
项目:logging-log4j2    文件:MdcPatternConverterTest.java   
@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));
}
项目:logging-log4j2    文件:MdcPatternConverterTest.java   
@Test
public void testConverterFullSingle() {
    ThreadContext.clearMap();
    ThreadContext.put("foo", "bar");
    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 = "{foo=bar}";
    assertTrue("Incorrect result. Expected " + expected + ", actual " + str, str.equals(expected));
}
项目:logging-log4j2    文件:PatternLayoutTest.java   
@Test
public void testUnixTime() throws Exception {
    final PatternLayout layout = PatternLayout.newBuilder().withPattern("%d{UNIX} %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() / 1000 + " Hello, world 1!", new String(result1));
    // System.out.println("event1=" + event1.getTimeMillis() / 1000);
    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() / 1000 + " Hello, world 2!", new String(result2));
    // System.out.println("event2=" + event2.getTimeMillis() / 1000);
}
项目:logging-log4j2    文件:MdcPatternConverterTest.java   
@Test
public void testConverterWithKeysAndPrefix() {
    final Message msg = new SimpleMessage("Hello");
    final String [] options = new String[] {"object, subject"};
    final MdcPatternConverter converter = MdcPatternConverter.newInstance(options);
    final LogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName("MyLogger") //
            .setLevel(Level.DEBUG) //
            .setMessage(msg) //
            .build();
    final StringBuilder sb = new StringBuilder();
    sb.append("prefix ");
    converter.format(event, sb);
    final String str = sb.toString();
    final String expected = "prefix {object=Log4j, subject=I}";
    assertEquals(expected, str);
}
项目:logging-log4j2    文件:MdcPatternConverterTest.java   
@Test
public void testConverterWithKeysSinglePresent() {
    final Message msg = new SimpleMessage("Hello");
    final String [] options = new String[] {"object, notpresent"};
    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 = "{object=Log4j}";
    assertEquals(expected, str);
}
项目:logging-log4j2    文件:MdcPatternConverterTest.java   
@Test
public void testConverterWithKeysNonePresent() {
    ThreadContext.clearMap();
    final Message msg = new SimpleMessage("Hello");
    final String [] options = new String[] {"object, subject"};
    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 = "{}";
    assertEquals(expected, str);
}
项目:logging-log4j2    文件:ConsoleAppenderTest.java   
private void testConsoleStreamManagerDoesNotClose(final PrintStream ps, final Target targetName, final SystemSetter systemSetter) {
    try {
        systemSetter.systemSet(psMock);
        final Layout<String> layout = PatternLayout.newBuilder().withAlwaysWriteExceptions(true).build();
        final ConsoleAppender app = ConsoleAppender.newBuilder().withLayout(layout).setTarget(targetName)
                .withName("Console").withIgnoreExceptions(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();
}
项目:logging-log4j2    文件:PatternParserTest.java   
@Test
public void testPatternTruncateFromEnd() {
    final List<PatternFormatter> formatters = parser.parse(patternTruncateFromEnd);
    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  org.a Hello, world" + Strings.LINE_SEPARATOR;
    assertTrue("Expected to end with: " + expected + ". Actual: " + str, str.endsWith(expected));
}
项目:logging-log4j2    文件:PatternParserTest.java   
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));
}