org.apache.logging.log4j.message.Message类的使用及代码示例

x33g5p2x  于2022-01-25 转载在 其他  
字(13.5k)|赞(0)|评价(0)|浏览(241)

本文整理了Java中org.apache.logging.log4j.message.Message类的一些代码示例,展示了Message类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Message类的具体详情如下:
包路径:org.apache.logging.log4j.message.Message
类名称:Message

Message介绍

[英]An interface for various Message implementations that can be logged. Messages can act as wrappers around Objects so that user can have control over converting Objects to Strings when necessary without requiring complicated formatters and as a way to manipulate the message based on information available at runtime such as the locale of the system.

Custom Message implementations should consider implementing the StringBuilderFormattableinterface for more efficient processing. Garbage-free Layouts will call StringBuilderFormattable#formatTo(StringBuilder) instead of Message#getFormattedMessage() if the Message implements StringBuilderFormattable.

Note: Message objects should not be considered to be thread safe nor should they be assumed to be safely reusable even on the same thread. The logging system may provide information to the Message objects and the Messages might be queued for asynchronous delivery. Thus, any modifications to a Message object by an application should by avoided after the Message has been passed as a parameter on a Logger method.
[中]一个可记录各种消息实现的接口。消息可以充当对象的包装器,这样用户就可以在必要时控制将对象转换为字符串,而不需要复杂的格式化程序,并且可以根据运行时可用的信息(如系统的区域设置)操纵消息。
自定义消息实现应该考虑实现StrugBueDeFrimeAtable接口以进行更高效的处理。如果消息实现了StringBuilderPerformAttable,则无垃圾布局将调用StringBuilderPerformAttable#formatTo(StringBuilder),而不是消息#getFormattedMessage()。
注意:消息对象不应该被认为是线程安全的,也不应该被认为是安全可重用的,即使在同一个线程上也是如此。日志系统可能会向消息对象提供信息,消息可能会排队等待异步传递。因此,在消息作为记录器方法上的参数传递后,应用程序应该避免对消息对象进行任何修改。

代码示例

代码示例来源:origin: Graylog2/graylog2-server

final Level logLevel = Level.toLevel(level, Level.ALL);
final MemoryAppender memoryAppender = (MemoryAppender) appender;
final List<InternalLogMessage> messages = new ArrayList<>(limit);
for (LogEvent event : memoryAppender.getLogMessages(limit)) {
  final Level eventLevel = event.getLevel();
  if (!eventLevel.isMoreSpecificThan(logLevel)) {
    continue;
  final ThrowableProxy thrownProxy = event.getThrownProxy();
  final String throwable;
  if (thrownProxy == null) {
  final Marker marker = event.getMarker();
  messages.add(InternalLogMessage.create(
      event.getMessage().getFormattedMessage(),
      event.getLoggerName(),
      eventLevel.toString(),
      marker == null ? null : marker.toString(),
      new DateTime(event.getTimeMillis(), DateTimeZone.UTC),

代码示例来源:origin: org.apache.logging.log4j/log4j-api

sb.append(getThreadName());
sb.append(SPACE);
sb.append(level.toString());
sb.append(SPACE);
sb.append(msg.getFormattedMessage());
final Object[] params = msg.getParameters();
Throwable t;
if (throwable == null && params != null && params[params.length - 1] instanceof Throwable) {

代码示例来源:origin: org.apache.logging.log4j/log4j-core

@Override
  public void format(final LogEvent event, final StringBuilder toAppendTo) {
    toAppendTo.append(event.getMessage().getFormat());
  }
}

代码示例来源:origin: io.sentry/sentry-log4j2

Message eventMessage = event.getMessage();
EventBuilder eventBuilder = new EventBuilder()
  .withSdkIntegration("log4j2")
  .withTimestamp(new Date(event.getTimeMillis()))
  .withMessage(eventMessage.getFormattedMessage())
  .withLogger(event.getLoggerName())
  .withLevel(formatLevel(event.getLevel()))
  .withExtra(THREAD_NAME, event.getThreadName());
if (eventMessage.getFormat() != null
  && !eventMessage.getFormat().equals("")
  && !eventMessage.getFormattedMessage().equals(eventMessage.getFormat())) {
  eventBuilder.withSentryInterface(new MessageInterface(
    eventMessage.getFormat(),
    formatMessageParameters(eventMessage.getParameters()),
    eventMessage.getFormattedMessage()));

代码示例来源:origin: org.apache.logging.log4j/log4j-core

protected void assertLogEvent(final LogEvent logEvent) {
    assertThat(logEvent, is(notNullValue()));
    assertThat(logEvent.getInstant().getEpochMillisecond(), equalTo(1493121664118L));
    assertThat(logEvent.getThreadName(), equalTo("main"));
    assertThat(logEvent.getThreadId(), equalTo(1L));
    assertThat(logEvent.getThreadPriority(), equalTo(5));
    assertThat(logEvent.getLevel(), equalTo(Level.INFO));
    assertThat(logEvent.getLoggerName(), equalTo("HelloWorld"));
    assertThat(logEvent.getMarker().getName(), equalTo("child"));
    assertThat(logEvent.getMarker().getParents()[0].getName(), equalTo("parent"));
    assertThat(logEvent.getMarker().getParents()[0].getParents()[0].getName(),
        equalTo("grandparent"));
    assertThat(logEvent.getMessage().getFormattedMessage(), equalTo("Hello, world!"));
    assertThat(logEvent.getThrown(), is(nullValue()));
    assertThat(logEvent.getThrownProxy().getMessage(), equalTo("error message"));
    assertThat(logEvent.getThrownProxy().getName(), equalTo("java.lang.RuntimeException"));
    assertThat(logEvent.getThrownProxy().getExtendedStackTrace()[0].getClassName(),
        equalTo("logtest.Main"));
    assertThat(logEvent.getLoggerFqcn(), equalTo("org.apache.logging.log4j.spi.AbstractLogger"));
    assertThat(logEvent.getContextStack().asList(), equalTo(Arrays.asList("one", "two")));
    assertThat((String) logEvent.getContextData().getValue("foo"), equalTo("FOO"));
    assertThat((String) logEvent.getContextData().getValue("bar"), equalTo("BAR"));
    assertThat(logEvent.getSource().getClassName(), equalTo("logtest.Main"));
  }
}

代码示例来源:origin: apache/geode

private void sendAlertMessage(final LogEvent event) {
 AlertMessaging alertMessaging = alertMessagingRef.get();
 if (alertMessaging == null || listeners.isEmpty()) {
  LOGGER.trace("Skipping alert messaging for {} because listeners is empty.", event);
  return;
 }
 AlertLevel alertLevel = AlertLevelConverter.fromLevel(event.getLevel());
 Date date = new Date(event.getTimeMillis());
 String threadName = event.getThreadName();
 String formattedMessage = event.getMessage().getFormattedMessage();
 String stackTrace = getStackTrace(event);
 for (AlertListener listener : listeners) {
  if (event.getLevel().intLevel() > listener.getLevel().intLevel()) {
   break;
  }
  LOGGER.trace("Sending alert message for {} to {}.", event, listener.getMember());
  alertMessaging.sendAlert(listener.getMember(), alertLevel, date, threadName, formattedMessage,
    stackTrace);
 }
}

代码示例来源:origin: apache/hive

@Override
public Result filter(LogEvent event) {
 if (event.getLevel().equals(Level.INFO) && "SessionState".equals(event.getLoggerName())) {
  if (event.getMessage().getFormattedMessage().startsWith("PREHOOK:")
    || event.getMessage().getFormattedMessage().startsWith("POSTHOOK:")
    || event.getMessage().getFormattedMessage().startsWith("unix_timestamp(void)")
    || event.getMessage().getFormattedMessage().startsWith("Warning: ")
    ) {
   return Result.ACCEPT;
  }
 }
 return Result.DENY;
}

代码示例来源:origin: ops4j/org.ops4j.pax.logging

sbuf.append(event.getTimeMillis() - jvmStartTime);
sbuf.append("</td>").append(Strings.LINE_SEPARATOR);
final String escapedThread = Transform.escapeHtmlTags(event.getThreadName());
sbuf.append("<td title=\"").append(escapedThread).append(" thread\">");
sbuf.append(escapedThread);
if (event.getLevel().equals(Level.DEBUG)) {
  sbuf.append("<font color=\"#339933\">");
  sbuf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel())));
  sbuf.append("</font>");
} else if (event.getLevel().isMoreSpecificThan(Level.WARN)) {
  sbuf.append("<font color=\"#993300\"><strong>");
  sbuf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel())));
sbuf.append(Transform.escapeHtmlTags(event.getMessage().getFormattedMessage()).replaceAll(REGEXP, "<br />"));
sbuf.append("</td>").append(Strings.LINE_SEPARATOR);
sbuf.append("</tr>").append(Strings.LINE_SEPARATOR);

代码示例来源:origin: com.kloudtek.mule.elogging/mule-elogging-log4j2

.put("loggerName", event.getLoggerName())
    .put("loggerFqcn", event.getLoggerFqcn())
    .put("threadName", event.getThreadName())
    .put("level", event.getLevel().name());
if (event.getMessage() instanceof MapMessage) {
  Map data = ((MapMessage) event.getMessage()).getData();
  json.put("message", event.getMessage().getFormattedMessage());
if (event.getThrownProxy() != null) {

代码示例来源:origin: org.apache.logging.log4j/log4j-core

@Override
public String toSerializable(final LogEvent event) {
  return event.getMessage().getFormattedMessage() + Strings.LINE_SEPARATOR;
}

代码示例来源:origin: net.openhft/chronicle-logger-log4j-2

@Override
public void doAppend(@NotNull final LogEvent event, @NotNull final ChronicleLogWriter writer) {
  writer.write(
      toChronicleLogLevel(event.getLevel()),
      event.getTimeMillis(),
      event.getThreadName(),
      event.getLoggerName(),
      event.getMessage().getFormattedMessage(),
      event.getThrown()
  );
}

代码示例来源:origin: org.apache.logging.log4j/log4j-core

@Test
  public void paramWithExceptionTest() throws Exception {
    logger.error("Throwing with parameters {}", "TestParam", new NullPointerException("Test Exception"));
    final List<LogEvent> events = app.getEvents();
    assertNotNull("Log event list not returned", events);
    assertEquals("Incorrect number of log events", 1, events.size());
    final LogEvent event = events.get(0);
    final Throwable thrown = event.getThrown();
    assertNotNull("No throwable present in log event", thrown);
    final Message msg = event.getMessage();
    assertEquals("Throwing with parameters {}", msg.getFormat());
    assertEquals("Throwing with parameters TestParam", msg.getFormattedMessage());
    assertArrayEquals(new Object[] { "TestParam", thrown }, msg.getParameters());
  }
}

代码示例来源:origin: com.github.emc-mongoose/mongoose-ui

public ShortenedLogEvent(final LogEvent logEvent) {
  level = logEvent.getLevel().name();
  loggerName = logEvent.getLoggerName();
  threadName = logEvent.getThreadName();
  timeStamp = logEvent.getTimeMillis();
  message = logEvent.getMessage().getFormattedMessage();
}

代码示例来源:origin: org.talend.daikon/logging-event-layout

Map<String, String> mdc = LayoutUtils.processMDCMetaFields(loggingEvent.getContextData().toMap(), logstashEvent,
    metaFields);
logstashEvent.put(LayoutFields.TIME_STAMP, LayoutUtils.dateFormat(loggingEvent.getTimeMillis()));
logstashEvent.put(LayoutFields.SEVERITY, loggingEvent.getLevel().toString());
logstashEvent.put(LayoutFields.THREAD_NAME, loggingEvent.getThreadName());
logstashEvent.put(LayoutFields.AGENT_TIME_STAMP, LayoutUtils.dateFormat(new Date().getTime()));
final String formattedMessage = loggingEvent.getMessage().getFormattedMessage();
if (formattedMessage != null) {
  logstashEvent.put(LayoutFields.LOG_MESSAGE, formattedMessage);

代码示例来源:origin: uk.gov.dwp.logging/encoded-logger-output

@Override
public String toSerializable(LogEvent le) {
  
  LogEntryBuilderFactory.LogEntryBuilder builder = logEntryBuilderFactory.getBuilder()
      .withLevel(le.getLevel().name())
      .withMessage(le.getMessage().getFormattedMessage())
      .withNameSpace(le.getLoggerName())
      .withTimeStamp(le.getNanoTime())
      .withMeta("thread", ""+le.getThreadId());
      
  
  Optional.ofNullable(le.getThrown())
      .ifPresent(
          thrown -> builder.withMeta(
              "exception", 
              String.join(
                  "\n", 
                  Throwables.toStringList(thrown)
                      .toArray(new String[0])
              )        
          )
      );
  
  return builder.build();
}

代码示例来源:origin: mulesoft/mule

@Override
public void append(LogEvent event) {
 expectations
   .add(new Expectation(event.getLevel().toString(), event.getLoggerName(), event.getMessage().getFormattedMessage()));
}

代码示例来源:origin: org.mycore/mycore-webcli

private String getJSONLogAsString(ObservableLogEventDeque events) {
  if (!events.isEmpty()) {
    LogEvent event = events.pollLast();
    JsonObject json = new JsonObject();
    json.addProperty("logLevel", event.getLevel().toString());
    json.addProperty("message", event.getMessage().getFormattedMessage());
    String exception = null;
    if (event.getThrownProxy() != null) {
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      event.getThrownProxy().getThrowable().printStackTrace(pw);
      pw.close();
      exception = sw.toString();
    }
    json.addProperty("exception", exception);
    json.addProperty("time", event.getTimeMillis());
    return json.toString();
  }
  return "";
}

代码示例来源:origin: org.apache.logging.log4j/log4j-core

LogEvent event = tcpTestServer.getQueue().poll(3, TimeUnit.SECONDS);
assertNotNull("No event retrieved", event);
assertTrue("Incorrect event", event.getMessage().getFormattedMessage().equals("This is a test message"));
assertTrue("Message not delivered via TCP", tcpTestServer.getCount() > 0);
assertEquals(expectedUuidStr, event.getContextData().getValue(tcKey));
event = tcpTestServer.getQueue().poll(3, TimeUnit.SECONDS);
assertNotNull("No event retrieved", event);
assertTrue("Incorrect event", event.getMessage().getFormattedMessage().equals("Throwing an exception"));
assertTrue("Message not delivered via TCP", tcpTestServer.getCount() > 1);
assertEquals(expectedUuidStr, event.getContextStack().pop());

代码示例来源:origin: org.apache.logging.log4j/log4j-api

@Override
public void logMessage(final String fqcn, final Level level, final Marker marker, final Message data, final Throwable t) {
  assertTrue("Incorrect Level. Expected " + currentLevel + ", actual " + level, level.equals(currentLevel));
  if (marker == null) {
    if (currentEvent.markerName != null) {
      fail("Incorrect message. Expected null. Actual is " + data.getFormattedMessage());
    } else {
      assertTrue("Incorrect message type. Expected " + currentEvent.data + ", actual " + data,
        data.getClass().isAssignableFrom(currentEvent.data.getClass()));
      assertTrue("Incorrect message. Expected " + currentEvent.data.getFormattedMessage() + ", actual " +
        data.getFormattedMessage(),
        currentEvent.data.getFormattedMessage().equals(data.getFormattedMessage()));

代码示例来源:origin: ops4j/org.ops4j.pax.logging

@Override
public Result filter(final LogEvent event) {
  final String text = useRawMessage ? event.getMessage().getFormat() : event.getMessage().getFormattedMessage();
  return filter(text);
}

相关文章