Java Code Examples for org.apache.logging.log4j.core.LogEvent#getMessage()

The following examples show how to use org.apache.logging.log4j.core.LogEvent#getMessage() . 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: MemoryAppender.java    From syncope with Apache License 2.0 6 votes vote down vote up
@Override
public void append(final LogEvent event) {
    LogStatement statement = new LogStatement();

    statement.setLevel(LoggerLevel.fromLevel(event.getLevel()));
    statement.setLoggerName(event.getLoggerName());

    Message msg = event.getMessage();
    statement.setMessage((msg instanceof ReusableMessage
            ? ((ReusableMessage) msg).memento()
            : msg).getFormattedMessage());

    statement.setTimeMillis(event.getTimeMillis());

    if (event.getThrown() != null) {
        statement.setStackTrace(ExceptionUtils2.getFullStackTrace(event.getThrown()));
    }

    statement.setThreadId(event.getThreadId());
    statement.setThreadName(event.getThreadName());
    statement.setThreadPriority(event.getThreadPriority());

    this.statements.add(statement);
}
 
Example 2
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 3
Source File: IbisXmlLayout.java    From iaf with Apache License 2.0 6 votes vote down vote up
@Override
protected String serializeEvent(LogEvent event) {
	XmlBuilder eventBuilder = XmlBuilder.create("event");
	eventBuilder.addAttribute("logger", event.getLoggerFqcn());
	eventBuilder.addAttribute("timestamp", ""+event.getTimeMillis());
	eventBuilder.addAttribute("level", event.getLevel().name());
	eventBuilder.addAttribute("thread", event.getThreadName());

	Message message = event.getMessage();
	XmlBuilder messageBuilder = XmlBuilder.create("message");
	messageBuilder.setElementContent(message.getFormattedMessage());
	eventBuilder.setSubElement(messageBuilder);

	Throwable t = message.getThrowable();
	if(t != null || alwaysWriteExceptions) {
		XmlBuilder throwableBuilder = XmlBuilder.create("throwable");
		StringWriter sw = new StringWriter();
		if(t != null) {
			t.printStackTrace(new PrintWriter(sw));
		}
		throwableBuilder.setElementContent(sw.toString());
		eventBuilder.setSubElement(throwableBuilder);
	}

	return eventBuilder.toString()+System.lineSeparator();
}
 
Example 4
Source File: Rfc5424Layout.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private void appendMessage(final StringBuilder buffer, final LogEvent event) {
    final Message message = event.getMessage();
    // This layout formats StructuredDataMessages instead of delegating to the Message itself.
    final String text = (message instanceof StructuredDataMessage || message instanceof MessageCollectionMessage)
            ? message.getFormat() : message.getFormattedMessage();

    if (text != null && text.length() > 0) {
        buffer.append(' ').append(escapeNewlines(text, escapeNewLine));
    }

    if (exceptionFormatters != null && event.getThrown() != null) {
        final StringBuilder exception = new StringBuilder(LF);
        for (final PatternFormatter formatter : exceptionFormatters) {
            formatter.format(event, exception);
        }
        buffer.append(escapeNewlines(exception.toString(), escapeNewLine));
    }
    if (includeNewLine) {
        buffer.append(LF);
    }
}
 
Example 5
Source File: RollbarAppender.java    From rollbar-java with MIT License 6 votes vote down vote up
@Override
public void append(LogEvent event) {
  if (event.getLoggerName() != null && event.getLoggerName().startsWith(PACKAGE_NAME)) {
    LOGGER.warn("Recursive logging from [{}] for appender [{}].", event.getLoggerName(),
        getName());
    return;
  }

  ThrowableProxy throwableProxy = event.getThrownProxy();
  ThrowableWrapper rollbarThrowableWrapper = buildRollbarThrowableWrapper(throwableProxy);
  Map<String, Object> custom = this.buildCustom(event);
  String message = event.getMessage() != null ? event.getMessage().getFormattedMessage() : null;
  Level level = this.getLevel(event);

  rollbar.log(rollbarThrowableWrapper, custom, message, level, false);
}
 
Example 6
Source File: AsyncLoggerConfigDisruptor.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private LogEvent prepareEvent(final LogEvent event) {
    LogEvent logEvent = ensureImmutable(event);
    if (logEvent.getMessage() instanceof ReusableMessage) {
        if (logEvent instanceof Log4jLogEvent) {
            ((Log4jLogEvent) logEvent).makeMessageImmutable();
        } else if (logEvent instanceof MutableLogEvent) {
            // MutableLogEvents need to be translated into the RingBuffer by the MUTABLE_TRANSLATOR.
            // That translator calls MutableLogEvent.initFrom to copy the event, which will makeMessageImmutable the message.
            if (translator != MUTABLE_TRANSLATOR) { // should not happen...
                // TRANSLATOR expects an immutable LogEvent
                logEvent = ((MutableLogEvent) logEvent).createMemento();
            }
        } else { // custom log event, with a ReusableMessage
            showWarningAboutCustomLogEventWithReusableMessage(logEvent);
        }
    } else { // message is not a ReusableMessage; makeMessageImmutable it to prevent ConcurrentModificationExceptions
        InternalAsyncUtil.makeMessageImmutable(logEvent.getMessage()); // LOG4J2-1988, LOG4J2-1914
    }
    return logEvent;
}
 
Example 7
Source File: CatAppender4Log4j2.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
private void logTrace(LogEvent event) {
	
	String type = "Log4j";
	String name = event.getLevel().toString();
	Object message = event.getMessage();
	String data;

	if (message instanceof Throwable) {
		data = buildExceptionStack((Throwable) message);
	} else {
		data = event.getMessage().toString();
	}

	Throwable info = event.getThrown();

	if (info != null) {
		String 	  extra = ExceptionUtils.extractExtraMessage(info);
		if(extra != null){
			data += "\n" + extra;
		}
		data += '\n' + buildExceptionStack(info);
	}
	Cat.logTrace(type, name, Trace.SUCCESS, data);
}
 
Example 8
Source File: MapResolver.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public void resolve(
        final LogEvent logEvent,
        final JsonWriter jsonWriter) {
    final Message message = logEvent.getMessage();
    if (!(message instanceof MapMessage)) {
        jsonWriter.writeNull();
    } else {
        @SuppressWarnings("unchecked")
        MapMessage<?, Object> mapMessage = (MapMessage<?, Object>) message;
        final IndexedReadOnlyStringMap map = mapMessage.getIndexedReadOnlyStringMap();
        final Object value = map.getValue(key);
        if (stringified) {
            final String stringifiedValue = String.valueOf(value);
            jsonWriter.writeString(stringifiedValue);
        } else {
            jsonWriter.writeValue(value);
        }
    }
}
 
Example 9
Source File: MapMessageLookup.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Looks up the value for the key using the data in the LogEvent.
 * @param event The current LogEvent.
 * @param key  the key to be looked up, may be null
 * @return The value associated with the key.
 */
@Override
public String lookup(final LogEvent event, final String key) {
    final Message msg = event.getMessage();
    if (msg instanceof MapMessage) {
        try {
            MapMessage<?, ?> mapMessage = (MapMessage) msg;
            if (key == null || key.length() == 0 || key.equals("*")) {
                return mapMessage.asString(MapMessage.MapFormat.JAVA_UNQUOTED.name());
            }
            return mapMessage.get(key);
        } catch (final Exception ex) {
            LOGGER.warn(LOOKUP, "Error while getting property [{}].", key, ex);
            return null;
        }
    }
    return null;
}
 
Example 10
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 11
Source File: MapPatternConverter.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) {
    MapMessage msg;
    if (event.getMessage() instanceof MapMessage) {
        msg = (MapMessage) event.getMessage();
    } else {
        return;
    }
    // if there is no additional options, we output every single
    // Key/Value pair for the Map in a similar format to Hashtable.toString()
    if (key == null) {
        msg.formatTo(format, toAppendTo);
    } else {
        // otherwise they just want a single key output
        final String val = msg.get(key);

        if (val != null) {
            toAppendTo.append(val);
        }
    }
}
 
Example 12
Source File: StructuredDataFilter.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public Result filter(final LogEvent event) {
    final Message msg = event.getMessage();
    if (msg instanceof StructuredDataMessage) {
        return filter((StructuredDataMessage) msg);
    }
    return super.filter(event);
}
 
Example 13
Source File: LogSearchJsonLayout.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
private String getLogMessage(LogEvent logEvent) {
  String logMessage = logEvent.getMessage() != null ? logEvent.getMessage().getFormattedMessage() : "";
  if (logEvent.getThrown() != null) {
    logMessage += NEW_LINE;
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    logEvent.getThrown().printStackTrace(pw);
    logMessage += sw.toString();
  }
  return logMessage;
}
 
Example 14
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 15
Source File: MaskingRewritePolicyTest.java    From owasp-security-logging with Apache License 2.0 5 votes vote down vote up
@Test
public void testRewriteMultiMarker() {
	System.out.println("running testRewriteMultiMarker()");

	//get multi marker
	Marker multiMarker = SecurityMarkers.getMarker(SecurityMarkers.CONFIDENTIAL, SecurityMarkers.SECURITY_FAILURE);

	// test a logging event with the multi-marker
	LOGGER.info(Log4JMarkerConverter.convertMarker(multiMarker), "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 16
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, but it is not parameterized
 * so masking cannot take place.
 */
@Test
public void testRewriteConfidentialNoParams() {
	System.out.println("running testRewriteConfidentialNoParams()");

	// 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=" + SSN));
}
 
Example 17
Source File: MaskingRewritePolicyTest.java    From owasp-security-logging with Apache License 2.0 5 votes vote down vote up
@Test
public void testRewriteConfidentialNoMessage() {
	System.out.println("running testRewriteConfidentialNoMessage()");

	// test a logging event with null marker
	String nullString = null;
	LOGGER.info(nullString);
	LogEvent failEvent = appender.getEvents().get(0);
	Message message = failEvent.getMessage();

	System.out.println("Formatted message: " + message.getFormattedMessage());
	assertEquals(message.getFormattedMessage(), "null");
}
 
Example 18
Source File: MessagePatternConverter.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void format(final LogEvent event, final StringBuilder toAppendTo) {
    final Message msg = event.getMessage();
    if (msg instanceof StringBuilderFormattable) {

        final boolean doRender = textRenderer != null;
        final StringBuilder workingBuilder = doRender ? new StringBuilder(80) : toAppendTo;

        final int offset = workingBuilder.length();
        if (msg instanceof MultiFormatStringBuilderFormattable) {
            ((MultiFormatStringBuilderFormattable) msg).formatTo(formats, workingBuilder);
        } else {
            ((StringBuilderFormattable) msg).formatTo(workingBuilder);
        }

        // TODO can we optimize this?
        if (config != null && !noLookups) {
            for (int i = offset; i < workingBuilder.length() - 1; i++) {
                if (workingBuilder.charAt(i) == '$' && workingBuilder.charAt(i + 1) == '{') {
                    final String value = workingBuilder.substring(offset, workingBuilder.length());
                    workingBuilder.setLength(offset);
                    workingBuilder.append(config.getStrSubstitutor().replace(event, value));
                }
            }
        }
        if (doRender) {
            textRenderer.render(workingBuilder, toAppendTo);
        }
        return;
    }
    if (msg != null) {
        String result;
        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 19
Source File: Rfc5424Layout.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
private void appendStructuredElements(final StringBuilder buffer, final LogEvent event) {
    final Message message = event.getMessage();
    final boolean isStructured = message instanceof StructuredDataMessage ||
            message instanceof StructuredDataCollectionMessage;

    if (!isStructured && (fieldFormatters != null && fieldFormatters.isEmpty()) && !includeMdc) {
        buffer.append('-');
        return;
    }

    final Map<String, StructuredDataElement> sdElements = new HashMap<>();
    final Map<String, String> contextMap = event.getContextData().toMap();

    if (mdcRequired != null) {
        checkRequired(contextMap);
    }

    if (fieldFormatters != null) {
        for (final Map.Entry<String, FieldFormatter> sdElement : fieldFormatters.entrySet()) {
            final String sdId = sdElement.getKey();
            final StructuredDataElement elem = sdElement.getValue().format(event);
            sdElements.put(sdId, elem);
        }
    }

    if (includeMdc && contextMap.size() > 0) {
        final String mdcSdIdStr = mdcSdId.toString();
        final StructuredDataElement union = sdElements.get(mdcSdIdStr);
        if (union != null) {
            union.union(contextMap);
            sdElements.put(mdcSdIdStr, union);
        } else {
            final StructuredDataElement formattedContextMap = new StructuredDataElement(contextMap, mdcPrefix, false);
            sdElements.put(mdcSdIdStr, formattedContextMap);
        }
    }

    if (isStructured) {
        if (message instanceof MessageCollectionMessage) {
            for (StructuredDataMessage data : ((StructuredDataCollectionMessage)message)) {
                addStructuredData(sdElements, data);
            }
        } else {
            addStructuredData(sdElements, (StructuredDataMessage) message);
        }
    }

    if (sdElements.isEmpty()) {
        buffer.append('-');
        return;
    }

    for (final Map.Entry<String, StructuredDataElement> entry : sdElements.entrySet()) {
        formatStructuredElement(entry.getKey(), entry.getValue(), buffer, listChecker);
    }
}
 
Example 20
Source File: MessageLayout.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Override
public Message toSerializable(final LogEvent event) {
    return event.getMessage();
}