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

The following examples show how to use org.apache.logging.log4j.message.Message. 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: Log4J2DialogAppender.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static IdeaLoggingEvent extractLoggingEvent(@Nonnull Message message, @Nonnull Throwable throwable) {
  //noinspection ThrowableResultOfMethodCallIgnored
  Throwable rootCause = ExceptionUtil.getRootCause(throwable);
  if (rootCause instanceof LogEventException) {
    return ((LogEventException)rootCause).getLogMessage();
  }

  String strMessage = message.getFormattedMessage();
  ExceptionWithAttachments withAttachments = ExceptionUtil.findCause(throwable, ExceptionWithAttachments.class);
  if (withAttachments != null) {
    return LogMessageEx.createEvent(strMessage, ExceptionUtil.getThrowableText(throwable), withAttachments.getAttachments());
  }

  return new IdeaLoggingEvent(strMessage, throwable);
}
 
Example #2
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 #3
Source File: MdcPatternConverterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #4
Source File: MdcPatternConverterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #5
Source File: LoggingMessageTagSupport.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public final int doEndTag() throws JspException {
    final Log4jTaglibLogger logger = this.getLogger();
    final Level level = this.getLevel();
    final Marker marker = this.getMarker();

    if (TagUtils.isEnabled(logger, level, marker)) {
        final Object message = this.getMessage();
        final Throwable exception = this.getException();
        if (message instanceof Message) {
            logger.logIfEnabled(FQCN, level, marker, (Message) message, exception);
        } else if (message instanceof String) {
            Message data;
            if (this.attributes.size() > 0) {
                data = logger.getMessageFactory().newMessage((String) message, this.attributes.toArray());
            } else {
                data = logger.getMessageFactory().newMessage((String) message);
            }
            logger.logIfEnabled(FQCN, level, marker, data, exception);
        } else {
            logger.logIfEnabled(FQCN, level, marker, logger.getMessageFactory().newMessage(message), exception);
        }
    }

    return Tag.EVAL_PAGE;
}
 
Example #6
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 #7
Source File: EcsLayout.java    From ecs-logging-java with Apache License 2.0 6 votes vote down vote up
private void serializeMessage(StringBuilder builder, boolean gcFree, Message message, Throwable thrown) {
    if (message instanceof MultiformatMessage) {
        MultiformatMessage multiformatMessage = (MultiformatMessage) message;
        if (supportsJson(multiformatMessage)) {
            serializeJsonMessage(builder, multiformatMessage);
        } else {
            serializeSimpleMessage(builder, gcFree, message, thrown);
        }
    } else if (objectMessageJacksonSerializer != null && message instanceof ObjectMessage) {
        final StringBuilder jsonBuffer = EcsJsonSerializer.getMessageStringBuilder();
        objectMessageJacksonSerializer.formatTo(jsonBuffer, (ObjectMessage) message);
        addJson(builder, jsonBuffer);
    } else {
        serializeSimpleMessage(builder, gcFree, message, thrown);
    }
}
 
Example #8
Source File: RewriteAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void rewriteTest() {
    final StructuredDataMessage msg = new StructuredDataMessage("Test", "This is a test", "Service");
    msg.put("Key1", "Value1");
    msg.put("Key2", "Value2");
    EventLogger.logEvent(msg);
    final List<LogEvent> list = app.getEvents();
    assertNotNull("No events generated", list);
    assertTrue("Incorrect number of events. Expected 1, got " + list.size(), list.size() == 1);
    final LogEvent event = list.get(0);
    final Message m = event.getMessage();
    assertTrue("Message is not a StringMapMessage: " + m.getClass(), m instanceof StructuredDataMessage);
    final StructuredDataMessage message = (StructuredDataMessage) m;
    final Map<String, String> map = message.getData();
    assertNotNull("No Map", map);
    assertTrue("Incorrect number of map entries, expected 3 got " + map.size(), map.size() == 3);
    final String value = map.get("Key1");
    assertEquals("Apache", value);
}
 
Example #9
Source File: NoGcMessagePatternConverter.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void format(final LogEvent event, final StringBuilder toAppendTo) {
    final Message msg = event.getMessage();
    if (msg != null) {
        String result;
        if (msg instanceof NoGcMessage) {
            toAppendTo.append(((NoGcMessage) msg).get());
            return;
        }
        if (msg instanceof MultiformatMessage) {
            result = ((MultiformatMessage) msg).getFormattedMessage(formats);
        } else {
            result = msg.getFormattedMessage();
        }
        if (result != null) {
            toAppendTo.append(config != null && result.contains("${") ?
                    config.getStrSubstitutor().replace(event, result) : result);
        } else {
            toAppendTo.append("null");
        }
    }
}
 
Example #10
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 #11
Source File: Log4jErrorLogger.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void error(Object originator, Object message, Throwable throwable) {

	if (message instanceof Message) {
		getLogger(originator).error((Message) message, throwable);
	}
	else {
		getLogger(originator).error(message, throwable);
	}
}
 
Example #12
Source File: Log4jErrorLogger.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void info(Object originator, Object message) {

	if (message instanceof Message) {
		getLogger(originator).info((Message) message);
	}
	else {
		getLogger(originator).info(message);
	}
}
 
Example #13
Source File: Log4jErrorLogger.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void warn(Object originator, Object message, Throwable throwable) {

	if (message instanceof Message) {
		getLogger(originator).warn((Message) message, throwable);
	}
	else {
		getLogger(originator).warn(message, throwable);
	}
}
 
Example #14
Source File: Log4jErrorLogger.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void debug(Object originator, Object message, Throwable throwable) {

	if (message instanceof Message) {
		getLogger(originator).debug((Message) message, throwable);
	}
	else {
		getLogger(originator).debug(message, throwable);
	}
}
 
Example #15
Source File: JsonLayoutTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testLayoutRingBufferEventReusableMessageWithCurlyBraces() throws Exception {
    final boolean propertiesAsList = false;
    final AbstractJacksonLayout layout = JsonLayout.newBuilder()
            .setLocationInfo(false)
            .setProperties(false)
            .setPropertiesAsList(propertiesAsList)
            .setComplete(false)
            .setCompact(true)
            .setEventEol(false)
            .setCharset(StandardCharsets.UTF_8)
            .setIncludeStacktrace(true)
            .build();
    Message message = ReusableMessageFactory.INSTANCE.newMessage("Testing {}", new TestObj());
    try {
        RingBufferLogEvent ringBufferEvent = new RingBufferLogEvent();
        ringBufferEvent.setValues(
                null, "a.B", null, "f.q.c.n", Level.DEBUG, message,
                null, new SortedArrayStringMap(), ThreadContext.EMPTY_STACK, 1L,
                "threadName", 1, null, new SystemClock(), new DummyNanoClock());
        final String str = layout.toSerializable(ringBufferEvent);
        final String expectedMessage = "Testing " + TestObj.TO_STRING_VALUE;
        assertThat(str, containsString("\"message\":\"" + expectedMessage + '"'));
        final Log4jLogEvent actual = new Log4jJsonObjectMapper(propertiesAsList, true, false, false).readValue(str, Log4jLogEvent.class);
        assertEquals(expectedMessage, actual.getMessage().getFormattedMessage());
    } finally {
        ReusableMessageFactory.release(message);
    }
}
 
Example #16
Source File: Log4jErrorLogger.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public void trace(Object originator, Object message) {

	if (message instanceof Message) {
		getLogger(originator).trace((Message) message);
	}
	else {
		getLogger(originator).trace(message);
	}
}
 
Example #17
Source File: CategoryTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Tests Category.forcedLog.
 */
@Test
@SuppressWarnings("deprecation")
public void testForcedLog() {
    final MockCategory category = new MockCategory("org.example.foo");
    category.setAdditivity(false);
    ((org.apache.logging.log4j.core.Logger) category.getLogger()).addAppender(appender);
    category.info("Hello, World");
    final List<LogEvent> list = appender.getEvents();
    int events = list.size();
    assertTrue("Number of events should be 1, was " + events, events == 1);
    LogEvent event = list.get(0);
    Message msg = event.getMessage();
    assertNotNull("No message", msg);
    assertTrue("Incorrect Message type", msg instanceof ObjectMessage);
    Object[] objects = msg.getParameters();
    assertTrue("Incorrect Object type", objects[0] instanceof String);
    appender.clear();
    category.log(Priority.INFO, "Hello, World");
    events = list.size();
    assertTrue("Number of events should be 1, was " + events, events == 1);
    event = list.get(0);
    msg = event.getMessage();
    assertNotNull("No message", msg);
    assertTrue("Incorrect Message type", msg instanceof ObjectMessage);
    objects = msg.getParameters();
    assertTrue("Incorrect Object type", objects[0] instanceof String);
    appender.clear();
}
 
Example #18
Source File: MarkerPatternConverterTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testLookup() {
    final Message msg = new StructuredDataMessage("Test", "This is a test", "Audit");
    final Marker eventMarker = MarkerManager.getMarker("EVENT");
    final Marker auditMarker = MarkerManager.getMarker("AUDIT").setParents(eventMarker);
    final LogEvent event = Log4jLogEvent.newBuilder().setLoggerName("MyLogger").setMarker(auditMarker)
            .setLevel(Level.DEBUG).setMessage(msg).build();
    final StringBuilder sb = new StringBuilder();
    final MarkerPatternConverter converter = MarkerPatternConverter.newInstance(null);
    converter.format(event, sb);
    assertEquals(auditMarker.toString(), sb.toString());
}
 
Example #19
Source File: MaskingRewritePolicyTest.java    From owasp-security-logging with Apache License 2.0 5 votes vote down vote up
/**
 * This test case has the CONFIDENTIAL marker so the results should be
 * masked
 */
@Test
public void testRewriteConfidentialWithParams() {
	System.out.println("running testRewriteConfidentialWithParams()");

	// test a logging event with the CONFIDENTIAL marker
	LOGGER.info(Log4JMarkerConverter.convertMarker(SecurityMarkers.CONFIDENTIAL), "ssn={}", SSN);
	LogEvent failEvent = appender.getEvents().get(0);
	Message message = failEvent.getMessage();

	System.out.println("Formatted message: " + message.getFormattedMessage());
	assertTrue(message.getFormattedMessage().contains("ssn=" + MaskingRewritePolicy.MASKED_PASSWORD));
}
 
Example #20
Source File: MessagePatternConverterTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testMapMessageFormatJson() throws Exception {
    final MessagePatternConverter converter = MessagePatternConverter.newInstance(null, new String[]{"json"});
    Message msg = new StringMapMessage()
            .with("key", "val");
    LogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName("MyLogger") //
            .setLevel(Level.DEBUG) //
            .setMessage(msg).build();
    StringBuilder sb = new StringBuilder();
    converter.format(event, sb);
    assertEquals("Unexpected result", "{\"key\":\"val\"}", sb.toString());
}
 
Example #21
Source File: AbstractLoggerTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSupplierWithoutThrowable() {
    final ThrowableExpectingLogger logger = new ThrowableExpectingLogger(false);
    final ThrowableMessage message = new ThrowableMessage(null);
    final Supplier<Message> supplier = new Supplier<Message>() {
        @Override
        public Message get() {
            return message;
        }
    };

    logger.debug(supplier);
    logger.error(supplier);
    logger.fatal(supplier);
    logger.info(supplier);
    logger.trace(supplier);
    logger.warn(supplier);
    logger.log(Level.INFO, supplier);

    logger.debug(MARKER, supplier);
    logger.error(MARKER, supplier);
    logger.fatal(MARKER, supplier);
    logger.info(MARKER, supplier);
    logger.trace(MARKER, supplier);
    logger.warn(MARKER, supplier);
    logger.log(Level.INFO, MARKER, supplier);
}
 
Example #22
Source File: MessageAttributeConverterTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testConvert01() {
    final Message message = LOGGER.getMessageFactory().newMessage("Message #{} said [{}].", 3, "Hello");

    final String converted = this.converter.convertToDatabaseColumn(message);

    assertNotNull("The converted value should not be null.", converted);
    assertEquals("The converted value is not correct.", "Message #3 said [Hello].", converted);

    final Message reversed = this.converter.convertToEntityAttribute(converted);

    assertNotNull("The reversed value should not be null.", reversed);
    assertEquals("The reversed value is not correct.", "Message #3 said [Hello].", reversed.getFormattedMessage());
}
 
Example #23
Source File: AbstractLoggerTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testMessageSupplierWithThrowable() {
    final ThrowableExpectingLogger logger = new ThrowableExpectingLogger(true);
    final ThrowableMessage message = new ThrowableMessage(t);
    final MessageSupplier supplier = new MessageSupplier() {
        @Override
        public Message get() {
            return message;
        }
    };

    logger.debug(supplier);
    logger.error(supplier);
    logger.fatal(supplier);
    logger.info(supplier);
    logger.trace(supplier);
    logger.warn(supplier);
    logger.log(Level.INFO, supplier);

    logger.debug(MARKER, supplier);
    logger.error(MARKER, supplier);
    logger.fatal(MARKER, supplier);
    logger.info(MARKER, supplier);
    logger.trace(MARKER, supplier);
    logger.warn(MARKER, supplier);
    logger.log(Level.INFO, MARKER, supplier);
}
 
Example #24
Source File: AbstractLogger.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Logs entry to a method with location information.
 *
 * @param fqcn The fully qualified class name of the <b>caller</b>.
 * @param message the Message.
 * @return The EntryMessage.
 * @since 2.6
 */
protected EntryMessage enter(final String fqcn, final Message message) {
    EntryMessage flowMessage = null;
    if (isEnabled(Level.TRACE, ENTRY_MARKER, (Object) null, null)) {
        logMessageSafely(fqcn, Level.TRACE, ENTRY_MARKER, flowMessage = flowMessageFactory.newEntryMessage(message),
                null);
    }
    return flowMessage;
}
 
Example #25
Source File: RegexFilter.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public Result filter(final Logger logger, final Level level, final Marker marker, final Message msg,
        final Throwable t) {
    if (msg == null) {
        return onMismatch;
    }
    final String text = useRawMessage ? msg.getFormat() : msg.getFormattedMessage();
    return filter(text);
}
 
Example #26
Source File: Log4JFilterTest.java    From AuthMeReloaded with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void shouldNotFilterIrrelevantLogEvent() {
	// given
	Message message = mockMessage(NORMAL_COMMAND);
	LogEvent event = Mockito.mock(LogEvent.class);
	when(event.getMessage()).thenReturn(message);
	
	// when
	Result result = log4JFilter.filter(event);
	
	// then
	assertThat(result, equalTo(Result.NEUTRAL));
}
 
Example #27
Source File: MessageAttributeConverter.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public String convertToDatabaseColumn(final Message message) {
    if (message == null) {
        return null;
    }

    return message.getFormattedMessage();
}
 
Example #28
Source File: AccessLogPatternConverter.java    From Poseidon with Apache License 2.0 5 votes vote down vote up
/**
 * Formats LogEvent into a string builder.
 *
 * @param logEvent      event to format, may not be null.
 * @param stringBuilder string builder to which the formatted event will be appended.
 */
@Override
public void format(LogEvent logEvent, StringBuilder stringBuilder) {
    Message message = logEvent.getMessage();
    if (message instanceof IAccessLog) {
        format((IAccessLog) message, stringBuilder);
    }
}
 
Example #29
Source File: DefaultLogBuilder.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void logMessage(Message message) {
    try {
        logger.logMessage(level, marker, FQCN, location, message, throwable);
    } finally {
        inUse = false;
    }
}
 
Example #30
Source File: MessagePatternConverterTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testMapMessageFormatXml() throws Exception {
    final MessagePatternConverter converter = MessagePatternConverter.newInstance(null, new String[]{"xml"});
    Message msg = new StringMapMessage()
            .with("key", "val");
    LogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName("MyLogger") //
            .setLevel(Level.DEBUG) //
            .setMessage(msg).build();
    StringBuilder sb = new StringBuilder();
    converter.format(event, sb);
    assertEquals("Unexpected result", "<Map>\n  <Entry key=\"key\">val</Entry>\n</Map>", sb.toString());
}