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();
}
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);
}
}
}
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") };
}
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();
}
}
}
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)));
});
}
Aggregations