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

The following examples show how to use org.apache.logging.log4j.message.ObjectMessage. 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: JsonLayoutTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private String prepareJsonForObjectMessageAsJsonObjectTests(final int value, final boolean objectMessageAsJsonObject) {
  	final TestClass testClass = new TestClass();
testClass.setValue(value);
// @formatter:off
final Log4jLogEvent expected = Log4jLogEvent.newBuilder()
          .setLoggerName("a.B")
          .setLoggerFqcn("f.q.c.n")
          .setLevel(Level.DEBUG)
          .setMessage(new ObjectMessage(testClass))
          .setThreadName("threadName")
          .setTimeMillis(1).build();
      // @formatter:off
final AbstractJacksonLayout layout = JsonLayout.newBuilder()
		.setCompact(true)
		.setObjectMessageAsJsonObject(objectMessageAsJsonObject)
		.build();
      // @formatter:off
      return layout.toSerializable(expected);
  }
 
Example #2
Source File: MessageResolver.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private static boolean writeObjectMessage(
        final JsonWriter jsonWriter,
        final Message message) {

    // Check type.
    if (!(message instanceof ObjectMessage)) {
        return false;
    }

    // Serialize object.
    final ObjectMessage objectMessage = (ObjectMessage) message;
    final Object object = objectMessage.getParameter();
    jsonWriter.writeValue(object);
    return true;

}
 
Example #3
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 #4
Source File: LoggerTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void flowTracingString_SupplierOfObjectMessages() {
    final EntryMessage msg = logger.traceEntry("doFoo(a={}, b={})", new Supplier<Message>() {
        @Override
        public Message get() {
            return new ObjectMessage(1);
        }
    }, new Supplier<Message>() {
        @Override
        public Message get() {
            return new ObjectMessage(2);
        }
    });
    logger.traceExit(msg, 3);
    assertEquals(2, results.size());
    assertThat("Incorrect Entry", results.get(0), startsWith("ENTER[ FLOW ] TRACE Enter"));
    assertThat("Missing entry data", results.get(0), containsString("doFoo(a=1, b=2)"));
    assertThat("Incorrect Exit", results.get(1), startsWith("EXIT[ FLOW ] TRACE Exit"));
    assertThat("Missing exit data", results.get(1), containsString("doFoo(a=1, b=2): 3"));
}
 
Example #5
Source File: Category.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public void log(final Priority priority, final Object message) {
    if (isEnabledFor(priority)) {
        @SuppressWarnings("unchecked")
        final Message msg = message instanceof Map ? new MapMessage((Map) message) : new ObjectMessage(message);
        forcedLog(FQCN, priority, msg, null);
    }
}
 
Example #6
Source File: ScriptFilter.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 Object msg,
                     final Throwable t) {
    final SimpleBindings bindings = new SimpleBindings();
    bindings.put("logger", logger);
    bindings.put("level", level);
    bindings.put("marker", marker);
    bindings.put("message", msg instanceof String ? new SimpleMessage((String)msg) : new ObjectMessage(msg));
    bindings.put("parameters", null);
    bindings.put("throwable", t);
    bindings.putAll(configuration.getProperties());
    bindings.put("substitutor", configuration.getStrSubstitutor());
    final Object object = configuration.getScriptManager().execute(script.getName(), bindings);
    return object == null || !Boolean.TRUE.equals(object) ? onMismatch : onMatch;
}
 
Example #7
Source File: SimpleModuleInitializer.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public void initialize(final SimpleModule simpleModule, final boolean objectMessageAsJsonObject) {
    // Workaround because mix-ins do not work for classes that already have a built-in deserializer.
    // See Jackson issue 429.
    simpleModule.addDeserializer(StackTraceElement.class, new Log4jStackTraceElementDeserializer());
    simpleModule.addDeserializer(ContextStack.class, new MutableThreadContextStackDeserializer());
    if (objectMessageAsJsonObject) {
        simpleModule.addSerializer(ObjectMessage.class, new ObjectMessageSerializer());
    }
    simpleModule.addSerializer(Message.class, new MessageSerializer());
}
 
Example #8
Source File: JsonTemplateLayoutTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void test_ObjectMessage() {

    // Create the log event.
    final int id = 0xDEADBEEF;
    final String name = "name-" + id;
    final Object attachment = new LinkedHashMap<String, Object>() {{
        put("id", id);
        put("name", name);
    }};
    final ObjectMessage message = new ObjectMessage(attachment);
    final LogEvent logEvent = Log4jLogEvent
            .newBuilder()
            .setLoggerName(LOGGER_NAME)
            .setLevel(Level.INFO)
            .setMessage(message)
            .build();

    // Create the event template.
    final String eventTemplate = writeJson(Map(
            "message", Map("$resolver", "message")));

    // Create the layout.
    JsonTemplateLayout layout = JsonTemplateLayout
            .newBuilder()
            .setConfiguration(CONFIGURATION)
            .setStackTraceEnabled(true)
            .setEventTemplate(eventTemplate)
            .build();

    // Check the serialized event.
    usingSerializedLogEventAccessor(layout, logEvent, accessor -> {
        assertThat(accessor.getInteger(new String[]{"message", "id"})).isEqualTo(id);
        assertThat(accessor.getString(new String[]{"message", "name"})).isEqualTo(name);
    });

}
 
Example #9
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 #10
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 #11
Source File: Category.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void maybeLog(final String fqcn, final org.apache.logging.log4j.Level level,
        final Object message, final Throwable throwable) {
    if (logger.isEnabled(level)) {
        if (logger instanceof ExtendedLogger) {
            ((ExtendedLogger) logger).logMessage(fqcn, level, null, new ObjectMessage(message), throwable);
        } else {
            logger.log(level, message, throwable);
        }
    }
}
 
Example #12
Source File: Category.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public void forcedLog(final String fqcn, final Priority level, final Object message, final Throwable t) {
    final org.apache.logging.log4j.Level lvl = org.apache.logging.log4j.Level.toLevel(level.toString());
    ObjectRenderer renderer = get(message.getClass());
    final Message msg = message instanceof Message ? (Message) message : renderer != null ?
        new RenderedMessage(renderer, message) : new ObjectMessage(message);
    if (logger instanceof ExtendedLogger) {
        ((ExtendedLogger) logger).logMessage(fqcn, lvl, null, new ObjectMessage(message), t);
    } else {
        logger.log(lvl, msg, t);
    }
}
 
Example #13
Source File: Category.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void maybeLog(final String fqcn, final org.apache.logging.log4j.Level level,
        final Object message, final Throwable throwable) {
    if (logger.isEnabled(level)) {
        @SuppressWarnings("unchecked")
        Message msg = message instanceof Map ? new MapMessage((Map) message) : new ObjectMessage(message);
        if (logger instanceof ExtendedLogger) {
            ((ExtendedLogger) logger).logMessage(fqcn, level, null, msg, throwable);
        } else {
            logger.log(level, msg, throwable);
        }
    }
}
 
Example #14
Source File: Category.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public void log(final Priority priority, final Object message, final Throwable t) {
    if (isEnabledFor(priority)) {
        @SuppressWarnings("unchecked")
        final Message msg = message instanceof Map ? new MapMessage((Map) message) : new ObjectMessage(message);
        forcedLog(FQCN, priority, msg, t);
    }
}
 
Example #15
Source File: LoggerSupplierTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void flowTracing_SupplierOfObjectMessage() {
    logger.traceEntry(new Supplier<ObjectMessage>() {
        @Override
        public ObjectMessage get() {
            return new ObjectMessage(1234567890);
        }
    });
    assertEquals(1, results.size());
    assertThat("Incorrect Entry", results.get(0), startsWith("ENTER[ FLOW ] TRACE Enter"));
    assertThat("Missing entry data", results.get(0), containsString("(1234567890)"));
    assertThat("Bad toString()", results.get(0), not(containsString("ObjectMessage")));
}
 
Example #16
Source File: ObjectMessageJacksonSerializer.java    From ecs-logging-java with Apache License 2.0 5 votes vote down vote up
@Override
public void formatTo(StringBuilder buffer, ObjectMessage objectMessage) {
    try {
        objectMapper.writeValue(new StringBuilderWriter(buffer), objectMessage.getParameter());
    } catch (IOException e) {
        StatusLogger.getLogger().catching(e);
        objectMessage.formatTo(buffer);
    }
}
 
Example #17
Source File: AbstractLog4j2EcsLayoutTest.java    From ecs-logging-java with Apache License 2.0 5 votes vote down vote up
@Test
void testJsonMessageObject() throws Exception {
    root.info(new ObjectMessage(new TestClass("foo", 42, true)));

    assertThat(getLastLogLine().get("foo").textValue()).isEqualTo("foo");
    assertThat(getLastLogLine().get("bar").intValue()).isEqualTo(42);
    assertThat(getLastLogLine().get("baz").booleanValue()).isEqualTo(true);
}
 
Example #18
Source File: AbstractLog4j2EcsLayoutTest.java    From ecs-logging-java with Apache License 2.0 5 votes vote down vote up
@Test
void testJsonMessageArray() throws Exception {
    root.info(new ObjectMessage(List.of("foo", "bar")));

    assertThat(getLastLogLine().get("message").isArray()).isFalse();
    assertThat(getLastLogLine().get("message").textValue()).isEqualTo("[\"foo\",\"bar\"]");
}
 
Example #19
Source File: AbstractLog4j2EcsLayoutTest.java    From ecs-logging-java with Apache License 2.0 5 votes vote down vote up
@Test
void testJsonMessageNumber() throws Exception {
    root.info(new ObjectMessage(42));

    assertThat(getLastLogLine().get("message").isNumber()).isFalse();
    assertThat(getLastLogLine().get("message").textValue()).isEqualTo("42");
}
 
Example #20
Source File: AuditLogger.java    From feast with Apache License 2.0 5 votes vote down vote up
/**
 * Log to stdout a json formatted audit log.
 *
 * @param resource type of resource
 * @param id id of resource, if any
 * @param action action taken
 * @param detail additional detail. Supports string formatting.
 * @param args arguments to the detail string
 */
public static void log(
    Resource resource, String id, Action action, String detail, Object... args) {
  Map<String, String> map = new TreeMap<>();
  map.put("timestamp", new Date().toString());
  map.put("resource", resource.toString());
  map.put("id", id);
  map.put("action", action.toString());
  map.put("detail", Strings.lenientFormat(detail, args));
  ObjectMessage msg = new ObjectMessage(map);

  log.log(AUDIT_LEVEL, msg);
}
 
Example #21
Source File: AbstractLog4j2EcsLayoutTest.java    From ecs-logging-java with Apache License 2.0 5 votes vote down vote up
@Test
void testJsonMessageBoolean() throws Exception {
    root.info(new ObjectMessage(true));

    assertThat(getLastLogLine().get("message").isBoolean()).isFalse();
    assertThat(getLastLogLine().get("message").textValue()).isEqualTo("true");
}
 
Example #22
Source File: AbstractLoggerTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isEnabled(final Level level, final Marker marker, final Object data, final Throwable t) {
    objectCount++;
    return isEnabled(level, marker, new ObjectMessage(data), t);
}
 
Example #23
Source File: LevelTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void testLevelLogging() {
    final Marker marker = MarkerManager.getMarker("marker");
    final Message msg = new ObjectMessage("msg");
    final Throwable t = new Throwable("test");
    final Level[] levels = new Level[] { Level.TRACE, Level.DEBUG, Level.INFO, Level.WARN, Level.ERROR, Level.FATAL };
    final String[] names = new String[] { "levelTest", "levelTest.Trace", "levelTest.Debug", "levelTest.Info",
            "levelTest.Warn", "levelTest.Error", "levelTest.Fatal" };
    for (final Level level : levels) {
        for (final String name : names) {
            final Logger logger = context.getLogger(name);
            logger.log(level, msg); // Message
            logger.log(level, 123); // Object
            logger.log(level, name); // String
            logger.log(level, marker, msg); // Marker, Message
            logger.log(level, marker, 123); // Marker, Object
            logger.log(level, marker, name); // marker, String
            logger.log(level, msg, t); // Message, Throwable
            logger.log(level, 123, t); // Object, Throwable
            logger.log(level, name, "param1", "param2"); // String, Object...
            logger.log(level, name, t); // String, Throwable
            logger.log(level, marker, msg, t); // Marker, Message, Throwable
            logger.log(level, marker, 123, t); // Marker, Object, Throwable
            logger.log(level, marker, name, "param1", "param2"); // Marker, String, Object...
            logger.log(level, marker, name, t); // Marker, String, Throwable
        }
    }
    // Logger "levelTest" will not receive same events as "levelTest.Trace"
    int levelCount = names.length - 1;

    final int UNIT = 14;
    final Expected[] expectedResults = new Expected[] { //
    new Expected(listAll, UNIT * levelCount, "TRACE", "All"), //
            new Expected(listTrace, UNIT * levelCount--, "TRACE", "Trace"), //
            new Expected(listDebug, UNIT * levelCount--, "DEBUG", "Debug"), //
            new Expected(listInfo, UNIT * levelCount--, "INFO", "Info"), //
            new Expected(listWarn, UNIT * levelCount--, "WARN", "Warn"), //
            new Expected(listError, UNIT * levelCount--, "ERROR", "Error"), //
            new Expected(listFatal, UNIT * levelCount--, "FATAL", "Fatal"), //
    };
    for (final Expected expected : expectedResults) {
        final String description = expected.description;
        final List<LogEvent> events = expected.appender.getEvents();
        assertNotNull(description + ": No events", events);
        assertThat(events, hasSize(expected.expectedEventCount));
        final LogEvent event = events.get(0);
        assertEquals(
            description + ": Expected level " + expected.expectedInitialEventLevel + ", got" + event.getLevel(),
            event.getLevel().name(), expected.expectedInitialEventLevel);
    }
}
 
Example #24
Source File: ObjectMessageSerializer.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Override
public void serialize(final ObjectMessage value, final JsonGenerator jsonGenerator,
        final SerializerProvider serializerProvider) throws IOException, JsonGenerationException {
    jsonGenerator.writeObject(value.getParameter());
}
 
Example #25
Source File: ObjectMessageSerializer.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
ObjectMessageSerializer() {
    super(ObjectMessage.class);
}
 
Example #26
Source File: AbstractLog4j2EcsLayoutTest.java    From ecs-logging-java with Apache License 2.0 4 votes vote down vote up
@Test
void testJsonMessageString() throws Exception {
    root.info(new ObjectMessage("foo"));

    assertThat(getLastLogLine().get("message").textValue()).isEqualTo("foo");
}
 
Example #27
Source File: Category.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
public void log(final String fqcn, final Priority priority, final Object message, final Throwable t) {
    if (isEnabledFor(priority)) {
        final Message msg = new ObjectMessage(message);
        forcedLog(fqcn, priority, msg, t);
    }
}
 
Example #28
Source File: Category.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
public void log(final Priority priority, final Object message) {
    if (isEnabledFor(priority)) {
        final Message msg = new ObjectMessage(message);
        forcedLog(FQCN, priority, msg, null);
    }
}
 
Example #29
Source File: Category.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
public void log(final Priority priority, final Object message, final Throwable t) {
    if (isEnabledFor(priority)) {
        final Message msg = new ObjectMessage(message);
        forcedLog(FQCN, priority, msg, t);
    }
}
 
Example #30
Source File: BufferedBulkOperationsTest.java    From log4j2-elasticsearch with Apache License 2.0 4 votes vote down vote up
@Test
public void defaultWriterCanSerializeBufferedBulk() throws IOException {

    // given
    PooledItemSourceFactory bufferedSourceFactory = PooledItemSourceFactoryTest.createDefaultTestSourceFactoryConfig().build();

    BufferedBulkOperations bufferedBulkOperations = new BufferedBulkOperations(bufferedSourceFactory);

    JacksonJsonLayout layout = createDefaultTestJacksonJsonLayout(bufferedSourceFactory);

    String expectedMessage = UUID.randomUUID().toString();
    long timeMillis = System.currentTimeMillis();
    Log4jLogEvent logEvent = Log4jLogEvent.newBuilder()
            .setTimeMillis(timeMillis)
            .setMessage(new ObjectMessage(expectedMessage)).build();

    ItemSource itemSource = layout.toSerializable(logEvent);

    String indexName = UUID.randomUUID().toString();
    BufferedIndex bufferedIndex = (BufferedIndex) bufferedBulkOperations.createBatchItem(indexName, itemSource);

    BatchBuilder<Bulk> batchBuilder = bufferedBulkOperations.createBatchBuilder();
    batchBuilder.add(bufferedIndex);

    // when
    ByteBuf byteBuf = ((BufferedBulk)batchBuilder.build()).serializeRequest();

    // then
    Scanner scanner = new Scanner(new ByteBufInputStream(byteBuf));

    TestIndex deserializedAction = new ObjectMapper()
            .addMixIn(TestIndex.class, BulkableActionMixIn.class)
            .readValue(scanner.nextLine(), TestIndex.class);
    assertEquals(indexName, deserializedAction.index);
    assertNotNull(deserializedAction.type);

    TestLogEvent deserializedDocument = new ObjectMapper().readValue(scanner.nextLine(), TestLogEvent.class);
    assertEquals(timeMillis, deserializedDocument.timeMillis);
    assertNotNull(deserializedDocument.level);
    assertNotNull(deserializedDocument.thread);
    assertEquals(expectedMessage, deserializedDocument.message);

}