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

The following examples show how to use org.apache.logging.log4j.message.ObjectMessage. These examples are extracted from open source projects. 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 Project: ecs-logging-java   Author: elastic   File: EcsLayout.java    License: 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 #2
Source Project: logging-log4j2   Author: apache   File: LoggerTest.java    License: 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 #3
Source Project: logging-log4j2   Author: apache   File: MessageResolver.java    License: 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 #4
Source Project: logging-log4j2   Author: apache   File: JsonLayoutTest.java    License: 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 #5
Source Project: ecs-logging-java   Author: elastic   File: ObjectMessageJacksonSerializer.java    License: 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 #6
Source Project: ecs-logging-java   Author: elastic   File: AbstractLog4j2EcsLayoutTest.java    License: 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 #7
Source Project: ecs-logging-java   Author: elastic   File: AbstractLog4j2EcsLayoutTest.java    License: 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 #8
Source Project: ecs-logging-java   Author: elastic   File: AbstractLog4j2EcsLayoutTest.java    License: 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 #9
Source Project: ecs-logging-java   Author: elastic   File: AbstractLog4j2EcsLayoutTest.java    License: 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 #10
Source Project: feast   Author: feast-dev   File: AuditLogger.java    License: 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 #11
Source Project: logging-log4j2   Author: apache   File: LoggerSupplierTest.java    License: 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 #12
Source Project: logging-log4j2   Author: apache   File: Category.java    License: 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 #13
Source Project: logging-log4j2   Author: apache   File: Category.java    License: 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 #14
Source Project: logging-log4j2   Author: apache   File: Category.java    License: 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 #15
Source Project: logging-log4j2   Author: apache   File: Category.java    License: 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 #16
Source Project: logging-log4j2   Author: apache   File: Category.java    License: 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 #17
Source Project: logging-log4j2   Author: apache   File: CategoryTest.java    License: 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 Project: logging-log4j2   Author: apache   File: CategoryTest.java    License: 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 #19
Source Project: logging-log4j2   Author: apache   File: JsonTemplateLayoutTest.java    License: 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 #20
Source Project: logging-log4j2   Author: apache   File: SimpleModuleInitializer.java    License: 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 #21
Source Project: logging-log4j2   Author: apache   File: ScriptFilter.java    License: 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 #22
Source Project: ecs-logging-java   Author: elastic   File: AbstractLog4j2EcsLayoutTest.java    License: 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 #23
Source Project: log4j2-elasticsearch   Author: rfoltyns   File: BufferedBulkOperationsTest.java    License: 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);

}
 
Example #24
Source Project: log4j2-elasticsearch   Author: rfoltyns   File: BufferedBulkOperationsTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void writerCanBeCustomizedWithMixins() throws IOException {

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

    BufferedBulkOperations bufferedBulkOperations = new BufferedBulkOperations(
            bufferedSourceFactory,
            new JacksonMixIn[]{
                    new JacksonMixIn.Builder()
                            .withTargetClass(BufferedIndex.class.getName())
                            .withMixInClass(TestBulkableActionMixIn.class.getName())
                            .build()
            },
            UUID.randomUUID().toString() // doesn't matter here..
    );

    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, TestBulkableActionMixIn.class)
            .readValue(scanner.nextLine(), TestIndex.class);
    assertNull(deserializedAction.type);

}
 
Example #25
Source Project: log4j2-elasticsearch   Author: rfoltyns   File: HCBatchOperationsTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void defaultWriterCanSerializeBatchRequest() throws IOException {

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

    String expectedType = UUID.randomUUID().toString();
    HCBatchOperations batchOperations = new HCBatchOperations(itemSourceFactory, expectedType);

    JacksonJsonLayout layout = createDefaultTestJacksonJsonLayout(itemSourceFactory);

    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();
    IndexRequest indexRequest = (IndexRequest) batchOperations.createBatchItem(indexName, itemSource);

    BatchBuilder<BatchRequest> batchBuilder = batchOperations.createBatchBuilder();
    batchBuilder.add(indexRequest);

    // when
    ByteBuf byteBuf = (ByteBuf) batchBuilder.build().serialize().getSource();

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

    TestIndex deserializedAction = new ObjectMapper()
            .addMixIn(TestIndex.class, IndexRequestMixIn.class)
            .readValue(scanner.nextLine(), TestIndex.class);
    assertEquals(indexName, deserializedAction.index);
    assertEquals(expectedType, 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);

}
 
Example #26
Source Project: logging-log4j2   Author: apache   File: TraceLoggingTest.java    License: 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 #27
Source Project: logging-log4j2   Author: apache   File: AbstractLoggerTest.java    License: 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 #28
Source Project: logging-log4j2   Author: apache   File: Category.java    License: 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 #29
Source Project: logging-log4j2   Author: apache   File: Category.java    License: 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 Project: logging-log4j2   Author: apache   File: Category.java    License: 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);
    }
}