Search in sources :

Example 1 with MapMessage

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

the class GcFreeLoggingTestUtil method executeLogging.

public static void executeLogging(final String configurationFile, final Class<?> testClass) throws Exception {
    System.setProperty("log4j2.enable.threadlocals", "true");
    System.setProperty("log4j2.enable.direct.encoders", "true");
    System.setProperty("log4j2.is.webapp", "false");
    System.setProperty("log4j.configurationFile", configurationFile);
    assertTrue("Constants.ENABLE_THREADLOCALS", Constants.ENABLE_THREADLOCALS);
    assertTrue("Constants.ENABLE_DIRECT_ENCODERS", Constants.ENABLE_DIRECT_ENCODERS);
    assertFalse("Constants.IS_WEB_APP", Constants.IS_WEB_APP);
    final MyCharSeq myCharSeq = new MyCharSeq();
    final Marker testGrandParent = MarkerManager.getMarker("testGrandParent");
    final Marker testParent = MarkerManager.getMarker("testParent").setParents(testGrandParent);
    // initial creation, value is cached
    final Marker test = MarkerManager.getMarker("test").setParents(testParent);
    // initialize LoggerContext etc.
    // This is not steady-state logging and will allocate objects.
    ThreadContext.put("aKey", "value1");
    ThreadContext.put("key2", "value2");
    final org.apache.logging.log4j.Logger logger = LogManager.getLogger(testClass.getName());
    logger.debug("debug not set");
    logger.fatal(test, "This message is logged to the console");
    logger.error("Sample error message");
    logger.error("Test parameterized message {}", "param");
    // initialize GelfLayout's messageStringBuilder
    logger.error(new MapMessage().with("eventId", "Login"));
    for (int i = 0; i < 256; i++) {
        // allocate MutableLogEvent.messageText
        logger.debug("ensure all ringbuffer slots have been used once");
    }
    ThreadContext.remove("aKey");
    ThreadContext.remove("key2");
    // BlockingWaitStrategy uses ReentrantLock which allocates Node objects. Ignore this.
    final String[] exclude = new String[] { //
    "java/util/concurrent/locks/AbstractQueuedSynchronizer$Node", //
    "com/google/monitoring/runtime/instrumentation/Sampler" };
    final AtomicBoolean samplingEnabled = new AtomicBoolean(true);
    final Sampler sampler = new Sampler() {

        @Override
        public void sampleAllocation(final int count, final String desc, final Object newObj, final long size) {
            if (!samplingEnabled.get()) {
                return;
            }
            for (int i = 0; i < exclude.length; i++) {
                if (exclude[i].equals(desc)) {
                    // exclude
                    return;
                }
            }
            System.err.println("I just allocated the object " + newObj + " of type " + desc + " whose size is " + size);
            if (count != -1) {
                System.err.println("It's an array of size " + count);
            }
            // show a stack trace to see which line caused allocation
            new RuntimeException().printStackTrace();
        }
    };
    Thread.sleep(500);
    final MapMessage mapMessage = new MapMessage().with("eventId", "Login");
    AllocationRecorder.addSampler(sampler);
    // now do some steady-state logging
    ThreadContext.put("aKey", "value1");
    ThreadContext.put("key2", "value2");
    final int ITERATIONS = 5;
    for (int i = 0; i < ITERATIONS; i++) {
        logger.error(myCharSeq);
        logger.error(MarkerManager.getMarker("test"), myCharSeq);
        logger.error("Test message");
        logger.error("Test parameterized message {}", "param");
        logger.error("Test parameterized message {}{}", "param", "param2");
        logger.error("Test parameterized message {}{}{}", "param", "param2", "abc");
        // LOG4J2-1683
        logger.error(mapMessage);
        ThreadContext.remove("aKey");
        ThreadContext.put("aKey", "value1");
    }
    Thread.sleep(50);
    // reliably ignore all allocations from now on
    samplingEnabled.set(false);
    AllocationRecorder.removeSampler(sampler);
    Thread.sleep(100);
}
Also used : MapMessage(org.apache.logging.log4j.message.MapMessage) Marker(org.apache.logging.log4j.Marker) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Sampler(com.google.monitoring.runtime.instrumentation.Sampler)

Example 2 with MapMessage

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

the class JmsAppenderIT method testLogMapMessageToQueue.

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

Example 3 with MapMessage

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

the class MapFilterTest method testFilter.

@Test
public void testFilter() {
    final KeyValuePair[] pairs = new KeyValuePair[] { new KeyValuePair("FromAccount", "211000"), new KeyValuePair("ToAccount", "123456") };
    MapFilter filter = MapFilter.createFilter(pairs, "and", null, null);
    filter.start();
    MapMessage msg = new MapMessage();
    msg.put("ToAccount", "123456");
    msg.put("FromAccount", "211000");
    msg.put("Amount", "1000.00");
    assertTrue(filter.isStarted());
    assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.DEBUG, null, msg, null));
    msg.put("ToAccount", "111111");
    assertSame(Filter.Result.DENY, filter.filter(null, Level.ERROR, null, msg, null));
    filter = MapFilter.createFilter(pairs, "or", null, null);
    filter.start();
    msg = new MapMessage();
    msg.put("ToAccount", "123456");
    msg.put("FromAccount", "211000");
    msg.put("Amount", "1000.00");
    assertTrue(filter.isStarted());
    assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.DEBUG, null, msg, null));
    msg.put("ToAccount", "111111");
    assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.ERROR, null, msg, null));
}
Also used : KeyValuePair(org.apache.logging.log4j.core.util.KeyValuePair) MapMessage(org.apache.logging.log4j.message.MapMessage) Test(org.junit.Test)

Example 4 with MapMessage

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

the class MapRewritePolicyTest method setupClass.

@BeforeClass
public static void setupClass() {
    map.put("test1", "one");
    map.put("test2", "two");
    logEvent0 = //
    Log4jLogEvent.newBuilder().setLoggerName(//
    "test").setContextMap(//
    map).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 MapMessage(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 MapMessage(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) 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) MapMessage(org.apache.logging.log4j.message.MapMessage) MutableThreadContextStack(org.apache.logging.log4j.spi.MutableThreadContextStack) BeforeClass(org.junit.BeforeClass)

Example 5 with MapMessage

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

the class MapLookupTest method testEventMapMessage.

@Test
public void testEventMapMessage() {
    final HashMap<String, String> map = new HashMap<>();
    map.put("A", "B");
    final HashMap<String, String> eventMap = new HashMap<>();
    eventMap.put("A1", "B1");
    final MapMessage message = new MapMessage(eventMap);
    final LogEvent event = Log4jLogEvent.newBuilder().setMessage(message).build();
    final MapLookup lookup = new MapLookup(map);
    assertEquals("B", lookup.lookup(event, "A"));
    assertEquals("B1", lookup.lookup(event, "A1"));
}
Also used : HashMap(java.util.HashMap) Log4jLogEvent(org.apache.logging.log4j.core.impl.Log4jLogEvent) LogEvent(org.apache.logging.log4j.core.LogEvent) MapMessage(org.apache.logging.log4j.message.MapMessage) Test(org.junit.Test)

Aggregations

MapMessage (org.apache.logging.log4j.message.MapMessage)13 Test (org.junit.Test)8 LogEvent (org.apache.logging.log4j.core.LogEvent)6 Log4jLogEvent (org.apache.logging.log4j.core.impl.Log4jLogEvent)6 HashMap (java.util.HashMap)5 Message (org.apache.logging.log4j.message.Message)3 Logger (org.apache.logging.log4j.Logger)2 KeyValuePair (org.apache.logging.log4j.core.util.KeyValuePair)2 StructuredDataMessage (org.apache.logging.log4j.message.StructuredDataMessage)2 Sampler (com.google.monitoring.runtime.instrumentation.Sampler)1 List (java.util.List)1 Map (java.util.Map)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 ConcurrentMap (java.util.concurrent.ConcurrentMap)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 MessageConsumer (javax.jms.MessageConsumer)1 Marker (org.apache.logging.log4j.Marker)1 Filter (org.apache.logging.log4j.core.Filter)1 Configuration (org.apache.logging.log4j.core.config.Configuration)1 SimpleMessage (org.apache.logging.log4j.message.SimpleMessage)1