Search in sources :

Example 6 with SimpleMessage

use of org.apache.logging.log4j.message.SimpleMessage in project logging-log4j2 by apache.

the class JmsAppenderIT method testLogObjectMessageToQueue.

@Test
public void testLogObjectMessageToQueue() throws Exception {
    setUp(SerializedLayout.createLayout());
    final int messageCount = 100;
    final MessageConsumer messageConsumer = jmsManager.createMessageConsumer();
    final JmsQueueConsumer consumer = new JmsQueueConsumer(messageCount, ObjectMessage.class);
    messageConsumer.setMessageListener(consumer);
    final String messageText = "Hello, World!";
    final String loggerName = this.getClass().getName();
    for (int i = 0; i < messageCount; i++) {
        final LogEvent event = //
        Log4jLogEvent.newBuilder().setLoggerName(loggerName).setLoggerFqcn(loggerName).setLevel(//
        Level.INFO).setMessage(new SimpleMessage(messageText)).setThreadName(//
        Thread.currentThread().getName()).setTimeMillis(System.currentTimeMillis()).build();
        appender.append(event);
    }
    consumer.awaitAndAssertAllMessagesConsumed();
}
Also used : MessageConsumer(javax.jms.MessageConsumer) LogEvent(org.apache.logging.log4j.core.LogEvent) Log4jLogEvent(org.apache.logging.log4j.core.impl.Log4jLogEvent) SimpleMessage(org.apache.logging.log4j.message.SimpleMessage) Test(org.junit.Test)

Example 7 with SimpleMessage

use of org.apache.logging.log4j.message.SimpleMessage in project logging-log4j2 by apache.

the class Category method maybeLog.

void maybeLog(final String fqcn, final org.apache.logging.log4j.Level level, final Object message, final Throwable throwable) {
    if (logger.isEnabled(level)) {
        final Message msg;
        if (message instanceof String) {
            msg = new SimpleMessage((String) message);
        } else // SimpleMessage treats String and CharSequence differently, hence this else-if block.
        if (message instanceof CharSequence) {
            msg = new SimpleMessage((CharSequence) message);
        } else if (message instanceof Map) {
            @SuppressWarnings("unchecked") final Map<String, ?> map = (Map<String, ?>) message;
            msg = new MapMessage<>(map);
        } else {
            msg = new ObjectMessage(message);
        }
        if (logger instanceof ExtendedLogger) {
            ((ExtendedLogger) logger).logMessage(fqcn, level, null, msg, throwable);
        } else {
            logger.log(level, msg, throwable);
        }
    }
}
Also used : ExtendedLogger(org.apache.logging.log4j.spi.ExtendedLogger) SimpleMessage(org.apache.logging.log4j.message.SimpleMessage) ObjectMessage(org.apache.logging.log4j.message.ObjectMessage) MapMessage(org.apache.logging.log4j.message.MapMessage) Message(org.apache.logging.log4j.message.Message) LocalizedMessage(org.apache.logging.log4j.message.LocalizedMessage) ObjectMessage(org.apache.logging.log4j.message.ObjectMessage) SimpleMessage(org.apache.logging.log4j.message.SimpleMessage) RendererMap(org.apache.log4j.or.RendererMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) Map(java.util.Map)

Example 8 with SimpleMessage

use of org.apache.logging.log4j.message.SimpleMessage in project logging-log4j2 by apache.

the class MapRewritePolicyTest method setupClass.

@BeforeAll
public static void setupClass() {
    stringMap.putValue("test1", "one");
    stringMap.putValue("test2", "two");
    map = stringMap.toMap();
    logEvent0 = // 
    Log4jLogEvent.newBuilder().setLoggerName(// 
    "test").setContextData(// 
    stringMap).setLoggerFqcn(// 
    "MapRewritePolicyTest.setupClass()").setLevel(// 
    Level.ERROR).setMessage(// 
    new SimpleMessage("Test")).setThrown(// 
    new RuntimeException("test")).setThreadName("none").setSource(new StackTraceElement("MapRewritePolicyTest", "setupClass", "MapRewritePolicyTest", 28)).setTimeMillis(2).build();
    logEvent1 = // 
    ((Log4jLogEvent) logEvent0).asBuilder().setMessage(// 
    new StringMapMessage(map)).setSource(// 
    new StackTraceElement("MapRewritePolicyTest", "setupClass", "MapRewritePolicyTest", 29)).build();
    final ThreadContextStack stack = new MutableThreadContextStack(new ArrayList<>(map.values()));
    logEvent2 = // 
    ((Log4jLogEvent) logEvent0).asBuilder().setContextStack(// 
    stack).setMarker(// 
    MarkerManager.getMarker("test")).setLevel(// 
    Level.TRACE).setMessage(// 
    new StructuredDataMessage("test", "Nothing", "test", map)).setTimeMillis(// 
    20000000).setSource(// 
    new StackTraceElement("MapRewritePolicyTest", "setupClass", "MapRewritePolicyTest", 30)).build();
    logEvent3 = // 
    ((Log4jLogEvent) logEvent0).asBuilder().setContextStack(// 
    stack).setLevel(// 
    Level.ALL).setMessage(// 
    new StringMapMessage(map)).setTimeMillis(// 
    Long.MAX_VALUE).setSource(// 
    new StackTraceElement("MapRewritePolicyTest", "setupClass", "MapRewritePolicyTest", 31)).build();
    rewrite = new KeyValuePair[] { new KeyValuePair("test2", "2"), new KeyValuePair("test3", "three") };
}
Also used : MutableThreadContextStack(org.apache.logging.log4j.spi.MutableThreadContextStack) ThreadContextStack(org.apache.logging.log4j.spi.ThreadContextStack) StringMapMessage(org.apache.logging.log4j.message.StringMapMessage) StructuredDataMessage(org.apache.logging.log4j.message.StructuredDataMessage) KeyValuePair(org.apache.logging.log4j.core.util.KeyValuePair) Log4jLogEvent(org.apache.logging.log4j.core.impl.Log4jLogEvent) SimpleMessage(org.apache.logging.log4j.message.SimpleMessage) MutableThreadContextStack(org.apache.logging.log4j.spi.MutableThreadContextStack) BeforeAll(org.junit.jupiter.api.BeforeAll)

Example 9 with SimpleMessage

use of org.apache.logging.log4j.message.SimpleMessage in project logging-log4j2 by apache.

the class RollingAppenderDirectWriteWithHtmlLayoutTest method checkAppenderWithHtmlLayout.

private void checkAppenderWithHtmlLayout(boolean append) throws InterruptedException, IOException {
    String prefix = "testHtml_" + (append ? "append_" : "noAppend_");
    Configuration config = loggerContextRule.getConfiguration();
    RollingFileAppender appender = RollingFileAppender.newBuilder().setName("RollingHtml").setFilePattern(DIR + "/" + prefix + "_-%d{MM-dd-yy-HH-mm}-%i.html").setPolicy(new SizeBasedTriggeringPolicy(500)).setStrategy(DirectWriteRolloverStrategy.newBuilder().setConfig(config).build()).setLayout(HtmlLayout.createDefaultLayout()).setAppend(append).build();
    boolean stopped = false;
    try {
        int count = 100;
        for (int i = 0; i < count; ++i) {
            appender.append(Log4jLogEvent.newBuilder().setMessage(new SimpleMessage("This is test message number " + i)).build());
        }
        appender.getManager().flush();
        appender.stop();
        stopped = true;
        Thread.sleep(50);
        final File dir = new File(DIR);
        assertTrue("Directory not created", dir.exists());
        final File[] files = dir.listFiles();
        assertNotNull(files);
        assertThat(files, hasItemInArray(that(hasName(that(endsWith(".html"))))));
        int foundEvents = 0;
        final Pattern eventMatcher = Pattern.compile("title=\"Message\"");
        for (File file : files) {
            if (!file.getName().startsWith(prefix))
                continue;
            try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                String data = IOUtils.toString(reader).trim();
                // check that every file starts with the header
                assertThat("header in file " + file, data, Matchers.startsWith("<!DOCTYPE"));
                assertThat("footer in file " + file, data, Matchers.endsWith("</html>"));
                final Matcher matcher = eventMatcher.matcher(data);
                while (matcher.find()) {
                    foundEvents++;
                }
            }
        }
        assertEquals("Incorrect number of events read.", count, foundEvents);
    } finally {
        if (!stopped) {
            appender.stop();
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) Configuration(org.apache.logging.log4j.core.config.Configuration) Matcher(java.util.regex.Matcher) RollingFileAppender(org.apache.logging.log4j.core.appender.RollingFileAppender) SimpleMessage(org.apache.logging.log4j.message.SimpleMessage)

Example 10 with SimpleMessage

use of org.apache.logging.log4j.message.SimpleMessage in project logging-log4j2 by apache.

the class JsonTemplateLayoutTest method test_timestamp_epoch_resolvers.

@Test
@SuppressWarnings("FloatingPointLiteralPrecision")
void test_timestamp_epoch_resolvers() {
    final List<Map<String, Object>> testCases = Arrays.asList(asMap("epochSecs", new BigDecimal("1581082727.982123456"), "epochSecsRounded", 1581082727, "epochSecsNanos", 982123456, "epochMillis", new BigDecimal("1581082727982.123456"), "epochMillisRounded", 1581082727982L, "epochMillisNanos", 123456, "epochNanos", 1581082727982123456L), asMap("epochSecs", new BigDecimal("1591177590.005000001"), "epochSecsRounded", 1591177590, "epochSecsNanos", 5000001, "epochMillis", new BigDecimal("1591177590005.000001"), "epochMillisRounded", 1591177590005L, "epochMillisNanos", 1, "epochNanos", 1591177590005000001L));
    // Create the event template.
    final String eventTemplate = writeJson(asMap("epochSecs", asMap("$resolver", "timestamp", "epoch", asMap("unit", "secs")), "epochSecsRounded", asMap("$resolver", "timestamp", "epoch", asMap("unit", "secs", "rounded", true)), "epochSecsNanos", asMap("$resolver", "timestamp", "epoch", asMap("unit", "secs.nanos")), "epochMillis", asMap("$resolver", "timestamp", "epoch", asMap("unit", "millis")), "epochMillisRounded", asMap("$resolver", "timestamp", "epoch", asMap("unit", "millis", "rounded", true)), "epochMillisNanos", asMap("$resolver", "timestamp", "epoch", asMap("unit", "millis.nanos")), "epochNanos", asMap("$resolver", "timestamp", "epoch", asMap("unit", "nanos"))));
    // Create the layout.
    final JsonTemplateLayout layout = JsonTemplateLayout.newBuilder().setConfiguration(CONFIGURATION).setEventTemplate(eventTemplate).build();
    testCases.forEach(testCase -> {
        // Create the log event.
        final SimpleMessage message = new SimpleMessage("Hello, World!");
        final Level level = Level.ERROR;
        final MutableInstant instant = new MutableInstant();
        final Object instantSecsObject = testCase.get("epochSecsRounded");
        final long instantSecs = instantSecsObject instanceof Long ? (long) instantSecsObject : (int) instantSecsObject;
        final int instantSecsNanos = (int) testCase.get("epochSecsNanos");
        instant.initFromEpochSecond(instantSecs, instantSecsNanos);
        final LogEvent logEvent = Log4jLogEvent.newBuilder().setLoggerName(LOGGER_NAME).setLevel(level).setMessage(message).setInstant(instant).build();
        // Verify the test case.
        usingSerializedLogEventAccessor(layout, logEvent, accessor -> testCase.forEach((key, expectedValue) -> Assertions.assertThat(accessor.getObject(key)).describedAs("key=%s", key).isEqualTo(expectedValue)));
    });
}
Also used : ParameterizedMessageFactory(org.apache.logging.log4j.message.ParameterizedMessageFactory) SimpleMessage(org.apache.logging.log4j.message.SimpleMessage) Arrays(java.util.Arrays) PluginFactory(org.apache.logging.log4j.plugins.PluginFactory) EventResolverContext(org.apache.logging.log4j.layout.template.json.resolver.EventResolverContext) MappingIterator(com.fasterxml.jackson.databind.MappingIterator) EventResolver(org.apache.logging.log4j.layout.template.json.resolver.EventResolver) ReusableMessageFactory(org.apache.logging.log4j.message.ReusableMessageFactory) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Level(org.apache.logging.log4j.Level) LogEvent(org.apache.logging.log4j.core.LogEvent) ByteBuffer(java.nio.ByteBuffer) Configuration(org.apache.logging.log4j.core.config.Configuration) ServerSocket(java.net.ServerSocket) BigDecimal(java.math.BigDecimal) ConfigurationBuilderFactory(org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) StringMapMessage(org.apache.logging.log4j.message.StringMapMessage) StringMap(org.apache.logging.log4j.util.StringMap) Assertions(org.assertj.core.api.Assertions) JsonNode(com.fasterxml.jackson.databind.JsonNode) TemplateResolver(org.apache.logging.log4j.layout.template.json.resolver.TemplateResolver) Log4jLogEvent(org.apache.logging.log4j.core.impl.Log4jLogEvent) JsonWriter(org.apache.logging.log4j.layout.template.json.util.JsonWriter) BlockingQueue(java.util.concurrent.BlockingQueue) Instant(java.time.Instant) EOFException(java.io.EOFException) Collectors(java.util.stream.Collectors) Test(org.junit.jupiter.api.Test) TemplateResolverConfig(org.apache.logging.log4j.layout.template.json.resolver.TemplateResolverConfig) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) MarkerManager(org.apache.logging.log4j.MarkerManager) List(java.util.List) Strings(org.apache.logging.log4j.util.Strings) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IntStream(java.util.stream.IntStream) ChronoField(java.time.temporal.ChronoField) TemplateResolverFactory(org.apache.logging.log4j.layout.template.json.resolver.TemplateResolverFactory) Socket(java.net.Socket) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectMessage(org.apache.logging.log4j.message.ObjectMessage) Severity(org.apache.logging.log4j.core.net.Severity) TemporalAccessor(java.time.temporal.TemporalAccessor) ArrayList(java.util.ArrayList) EventTemplateAdditionalField(org.apache.logging.log4j.layout.template.json.JsonTemplateLayout.EventTemplateAdditionalField) Message(org.apache.logging.log4j.message.Message) Charset(java.nio.charset.Charset) SocketAppender(org.apache.logging.log4j.core.appender.SocketAppender) MutableInstant(org.apache.logging.log4j.core.time.MutableInstant) ByteBufferDestination(org.apache.logging.log4j.core.layout.ByteBufferDestination) Marker(org.apache.logging.log4j.Marker) TestHelpers(org.apache.logging.log4j.layout.template.json.TestHelpers) PrintStream(java.io.PrintStream) MessageFactory(org.apache.logging.log4j.message.MessageFactory) SortedArrayStringMap(org.apache.logging.log4j.util.SortedArrayStringMap) EventResolverFactory(org.apache.logging.log4j.layout.template.json.resolver.EventResolverFactory) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) MainMapLookup(org.apache.logging.log4j.core.lookup.MainMapLookup) TimeUnit(java.util.concurrent.TimeUnit) AvailablePortFinder(org.apache.logging.log4j.core.test.AvailablePortFinder) Plugin(org.apache.logging.log4j.plugins.Plugin) Collections(java.util.Collections) InputStream(java.io.InputStream) LogEvent(org.apache.logging.log4j.core.LogEvent) Log4jLogEvent(org.apache.logging.log4j.core.impl.Log4jLogEvent) SimpleMessage(org.apache.logging.log4j.message.SimpleMessage) MutableInstant(org.apache.logging.log4j.core.time.MutableInstant) BigDecimal(java.math.BigDecimal) Level(org.apache.logging.log4j.Level) Map(java.util.Map) StringMap(org.apache.logging.log4j.util.StringMap) SortedArrayStringMap(org.apache.logging.log4j.util.SortedArrayStringMap) Test(org.junit.jupiter.api.Test)

Aggregations

SimpleMessage (org.apache.logging.log4j.message.SimpleMessage)198 Log4jLogEvent (org.apache.logging.log4j.core.impl.Log4jLogEvent)148 LogEvent (org.apache.logging.log4j.core.LogEvent)142 Test (org.junit.jupiter.api.Test)128 Message (org.apache.logging.log4j.message.Message)43 Marker (org.apache.logging.log4j.Marker)23 Test (org.junit.Test)21 StringMap (org.apache.logging.log4j.util.StringMap)20 Level (org.apache.logging.log4j.Level)17 IOException (java.io.IOException)13 SortedArrayStringMap (org.apache.logging.log4j.util.SortedArrayStringMap)12 ObjectMessage (org.apache.logging.log4j.message.ObjectMessage)11 ContextStack (org.apache.logging.log4j.ThreadContext.ContextStack)10 LoggerContext (org.apache.logging.log4j.core.LoggerContext)10 ClockFactoryTest (org.apache.logging.log4j.core.time.ClockFactoryTest)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 ReusableMessage (org.apache.logging.log4j.message.ReusableMessage)5 ReusableObjectMessage (org.apache.logging.log4j.message.ReusableObjectMessage)5 StringMapMessage (org.apache.logging.log4j.message.StringMapMessage)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4