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

The following examples show how to use org.apache.logging.log4j.core.LogEvent#getTimeMillis() . 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: RollingIndexNameFormatter.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public final String format(LogEvent event) {
    long eventTimeInMillis = event.getTimeMillis();

    // handle "old" events that arrived in separate threads after rollover
    if (eventTimeInMillis < currentFileTime) {
        return doFormat(indexName, eventTimeInMillis);
    }

    // rollover
    if (eventTimeInMillis >= nextRolloverTime && rollingOver.compareAndSet(false, true)) {
        rollover(indexName, eventTimeInMillis);
        rollingOver.set(false);
    }

    // happy path - have to check for pending rollover to avoid race conditions
    if (!rollingOver.get()) {
        return currentName;
    }

    // fail-safe for pending rollover
    return doFormat(indexName, eventTimeInMillis);
}
 
Example 2
Source File: SimpleDiagnosticsAppender.java    From samza with Apache License 2.0 6 votes vote down vote up
@Override
public void append(LogEvent logEvent) {
  try {
    // if an event with a non-null throwable is received => exception event
    if (logEvent.getThrown() != null) {
      DiagnosticsExceptionEvent diagnosticsExceptionEvent =
          new DiagnosticsExceptionEvent(logEvent.getTimeMillis(), logEvent.getThrown(),
              logEvent.getContextData().toMap());

      diagnosticsManager.addExceptionEvent(diagnosticsExceptionEvent);
    }
  } catch (Exception e) {
    // blanket catch of all exceptions so as to not impact any job
    System.err.println("Exception in logevent parsing " + e);
  }
}
 
Example 3
Source File: DatePatternConverterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testFormatLogEventStringBuilderIso8601TimezoneJST() {
    final LogEvent event = new MyLogEvent();
    final String[] optionsWithTimezone = {ISO8601, "JST"};
    final DatePatternConverter converter = DatePatternConverter.newInstance(optionsWithTimezone);
    final StringBuilder sb = new StringBuilder();
    converter.format(event, sb);

    // JST=Japan Standard Time: UTC+9:00
    final TimeZone tz = TimeZone.getTimeZone("JST");
    final SimpleDateFormat sdf = new SimpleDateFormat(converter.getPattern());
    sdf.setTimeZone(tz);
    final long adjusted = event.getTimeMillis() + tz.getDSTSavings();
    final String expected = sdf.format(new Date(adjusted));
    // final String expected = "2011-12-30T18:56:35,987"; // in CET (Central Eastern Time: Amsterdam)
    assertEquals(expected, sb.toString());
}
 
Example 4
Source File: DatePatternConverterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testFormatLogEventStringBuilderIso8601TimezoneZ() {
    final LogEvent event = new MyLogEvent();
    final String[] optionsWithTimezone = { ISO8601, "Z" };
    final DatePatternConverter converter = DatePatternConverter.newInstance(optionsWithTimezone);
    final StringBuilder sb = new StringBuilder();
    converter.format(event, sb);

    final TimeZone tz = TimeZone.getTimeZone("UTC");
    final SimpleDateFormat sdf = new SimpleDateFormat(converter.getPattern());
    sdf.setTimeZone(tz);
    final long adjusted = event.getTimeMillis() + tz.getDSTSavings();
    final String expected = sdf.format(new Date(adjusted));
    // final String expected = "2011-12-30T17:56:35,987"; // in UTC
    assertEquals(expected, sb.toString());
}
 
Example 5
Source File: CloudwatchLogsLog4J2Appender.java    From cloudwatchlogs-java-appender with Apache License 2.0 5 votes vote down vote up
@Override
public void append(LogEvent event) {
    StringBuilder message = new StringBuilder(event.getMessage().getFormattedMessage());
    Throwable thrown = event.getThrown();
    while (thrown != null) {
        message.append("\n").append(dump(thrown));
        thrown = thrown.getCause();
        if (thrown != null) {
            message.append("\nCaused by:");
        }
    }

    String account = event.getContextData().getValue(CloudwatchLogsMDCPropertyNames.ACCOUNT);
    String action = event.getContextData().getValue(CloudwatchLogsMDCPropertyNames.ACTION);
    String user = event.getContextData().getValue(CloudwatchLogsMDCPropertyNames.USER);
    String session = event.getContextData().getValue(CloudwatchLogsMDCPropertyNames.SESSION);
    String request = event.getContextData().getValue(CloudwatchLogsMDCPropertyNames.REQUEST);

    Marker marker = event.getMarker();
    String eventId = marker == null ? null : marker.getName();

    Map<String, String> customMdcAttributes = new HashMap<>();
    for (String key : config.getCustomMdcKeys()) {
        String value = event.getContextData().getValue(key);
        if (value != null) {
            customMdcAttributes.put(key, value);
        }
    }

    CloudwatchLogsLogEvent logEvent = new CloudwatchLogsLogEvent(event.getLevel().toString(), event.getLoggerName(),
            eventId, message.toString(), event.getTimeMillis(), event.getThreadName(), account, action, user,
            session, request, customMdcAttributes);
    while (!eventQueue.offer(logEvent)) {
        eventQueue.poll();
        discardedCount++;
    }
}
 
Example 6
Source File: JsonLog4j2Layout.java    From javalite with Apache License 2.0 5 votes vote down vote up
/**
 * Formats a {@link org.apache.logging.log4j.core.LogEvent}.
 *
 * @param event The LogEvent.
 * @return The XML representation of the LogEvent.
 */
@Override
public String toSerializable(final LogEvent event) {
    String loggerName = event.getLoggerName();
    String level = event.getLevel().toString();
    String message = event.getMessage().getFormattedMessage();
    if (!message.startsWith("{") && !message.startsWith("[")) {
        message = "\"" + message + "\"";
    }
    String threadName = event.getThreadName();
    Date timeStamp = new Date(event.getTimeMillis());
    String context = Context.toJSON();

    Throwable throwable = event.getThrown();

    String exception = "";
    if (throwable != null) {
        exception = ",\"exception\":{\"message\":\"";
        String exceptionMessage = throwable.getMessage() != null ? throwable.getMessage() : "";
        //need to be careful here, sanitizing, since the message may already contain a chunk of JSON, so escaping or cleaning double quotes is not prudent:)
        exception += sanitize(exceptionMessage, false, '\n', '\t', '\r') + "\",\"stacktrace\":\"" + escapeControlChars(Util.getStackTraceString(throwable)) + "\"}";
    }

    String contextJson = context != null ? ",\"context\":" + context : "";

    String timestampString = this.simpleDateFormat == null ? timeStamp.toString() : simpleDateFormat.format(timeStamp);

    return "{\"level\":\"" + level + "\",\"timestamp\":\"" + timestampString
            + "\",\"thread\":\"" + threadName + "\",\"logger\":\"" + loggerName + "\",\"message\":"
            + message + contextJson + exception + "}" + System.getProperty("line.separator");
}
 
Example 7
Source File: TimestampResolver.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void resolve(
        final LogEvent logEvent,
        final JsonWriter jsonWriter) {

    // Format timestamp if it doesn't match the last cached one.
    final long timestampMillis = logEvent.getTimeMillis();
    if (formatResolverContext.calendar.getTimeInMillis() != timestampMillis) {

        // Format the timestamp.
        formatResolverContext.formattedTimestampBuilder.setLength(0);
        formatResolverContext.calendar.setTimeInMillis(timestampMillis);
        formatResolverContext.timestampFormat.format(
                formatResolverContext.calendar,
                formatResolverContext.formattedTimestampBuilder);

        // Write the formatted timestamp.
        final StringBuilder jsonWriterStringBuilder = jsonWriter.getStringBuilder();
        final int startIndex = jsonWriterStringBuilder.length();
        jsonWriter.writeString(formatResolverContext.formattedTimestampBuilder);

        // Cache the written value.
        formatResolverContext.formattedTimestampBuilder.setLength(0);
        formatResolverContext.formattedTimestampBuilder.append(
                jsonWriterStringBuilder,
                startIndex,
                jsonWriterStringBuilder.length());

    }

    // Write the cached formatted timestamp.
    else {
        jsonWriter.writeRawString(
                formatResolverContext.formattedTimestampBuilder);
    }

}
 
Example 8
Source File: KafkaAppender.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void tryAppend(final LogEvent event) throws ExecutionException, InterruptedException, TimeoutException {
    final Layout<? extends Serializable> layout = getLayout();
    byte[] data;
    Long eventTimestamp;

    data = layout.toByteArray(event);
    eventTimestamp = event.getTimeMillis();
    manager.send(data, eventTimestamp);
}
 
Example 9
Source File: TimeBasedTriggeringPolicy.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Determines whether a rollover should occur.
 * @param event   A reference to the currently event.
 * @return true if a rollover should occur.
 */
@Override
public boolean isTriggeringEvent(final LogEvent event) {
    final long nowMillis = event.getTimeMillis();
    if (nowMillis >= nextRolloverMillis) {
        nextRolloverMillis = ThreadLocalRandom.current().nextLong(0, 1 + maxRandomDelayMillis)
                + manager.getPatternProcessor().getNextTime(nowMillis, interval, modulate);
        manager.getPatternProcessor().setCurrentFileTime(System.currentTimeMillis());
        return true;
    }
    return false;
}
 
Example 10
Source File: DatePatternConverterTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testFormatLogEventStringBuilderIso8601TimezoneUTC() {
    final LogEvent event = new MyLogEvent();
    final DatePatternConverter converter = DatePatternConverter.newInstance(new String[] {"ISO8601", "UTC"});
    final StringBuilder sb = new StringBuilder();
    converter.format(event, sb);

    final TimeZone tz = TimeZone.getTimeZone("UTC");
    final SimpleDateFormat sdf = new SimpleDateFormat(converter.getPattern());
    sdf.setTimeZone(tz);
    final long adjusted = event.getTimeMillis() + tz.getDSTSavings();
    final String expected = sdf.format(new Date(adjusted));
    // final String expected = "2011-12-30T09:56:35,987";
    assertEquals(expected, sb.toString());
}
 
Example 11
Source File: LoghubAppender.java    From aliyun-log-log4j2-appender with Apache License 2.0 4 votes vote down vote up
@Override
public void append(LogEvent event) {
    List<LogItem> logItems = new ArrayList<LogItem>();
    LogItem item = new LogItem();
    logItems.add(item);
    item.SetTime((int) (event.getTimeMillis() / 1000));
    DateTime dateTime = new DateTime(event.getTimeMillis());
    item.PushBack("time", dateTime.toString(formatter));
    item.PushBack("level", event.getLevel().toString());
    item.PushBack("thread", event.getThreadName());

    StackTraceElement source = event.getSource();
    if (source == null && (!event.isIncludeLocation())) {
        event.setIncludeLocation(true);
        source = event.getSource();
        event.setIncludeLocation(false);
    }

    item.PushBack("location", source == null ? "Unknown(Unknown Source)" : source.toString());

    String message = event.getMessage().getFormattedMessage();
    item.PushBack("message", message);

    String throwable = getThrowableStr(event.getThrown());
    if (throwable != null) {
        item.PushBack("throwable", throwable);
    }

    if (getLayout() != null) {
        item.PushBack("log", new String(getLayout().toByteArray(event)));
    }

    Optional.ofNullable(mdcFields).ifPresent(
            f->event.getContextMap().entrySet().stream()
                    .filter(v->Arrays.stream(f.split(",")).anyMatch(i->i.equals(v.getKey())))
                    .forEach(map-> item.PushBack(map.getKey(),map.getValue()))
    );
    try {
        producer.send(this.project, this.logStore, this.topic, this.source, logItems, new LoghubAppenderCallback(LOGGER,
                this.project, this.logStore, this.topic, this.source, logItems));
    } catch (Exception e) {
        this.error(
                "Failed to send log, project=" + project
                        + ", logStore=" + logStore
                        + ", topic=" + topic
                        + ", source=" + source
                        + ", logItem=" + logItems, e);
    }
}
 
Example 12
Source File: Log4j2Watcher.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public long getTimestamp(LogEvent event) {
  return event.getTimeMillis();
}
 
Example 13
Source File: LoggingEventJsonSerde.java    From samza with Apache License 2.0 4 votes vote down vote up
/**
 * Encodes a LoggingEvent into a HashMap using the logstash JSON format.
 *
 * @param loggingEvent
 *          The LoggingEvent to encode.
 * @param includeLocationInfo
 *          Whether to include LocationInfo in the map, or not.
 * @return A Map representing the LoggingEvent, which is suitable to be
 *         serialized by a JSON encoder such as Jackson.
 */
@SuppressWarnings("rawtypes")
public static Map<String, Object> encodeToMap(LogEvent loggingEvent, boolean includeLocationInfo) {
  Map<String, Object> logstashEvent = new LoggingEventJsonSerde.LoggingEventMap();
  String threadName = loggingEvent.getThreadName();
  long timestamp = loggingEvent.getTimeMillis();
  HashMap<String, Object> exceptionInformation = new HashMap<String, Object>();
  Map mdc = loggingEvent.getContextData().toMap();
  ThreadContext.ContextStack ndc = loggingEvent.getContextStack();

  logstashEvent.put("@version", VERSION);
  logstashEvent.put("@timestamp", dateFormat(timestamp));
  logstashEvent.put("source_host", getHostname());
  logstashEvent.put("message", loggingEvent.getMessage());

  if (loggingEvent.getThrown() != null) {
    final Throwable throwableInformation = loggingEvent.getThrown();
    if (throwableInformation.getClass().getCanonicalName() != null) {
      exceptionInformation.put("exception_class", throwableInformation.getClass().getCanonicalName());
    }
    if (throwableInformation.getMessage() != null) {
      exceptionInformation.put("exception_message", throwableInformation.getMessage());
    }
    if (throwableInformation.getMessage() != null) {
      StringBuilder stackTrace = new StringBuilder(ExceptionUtils.getStackTrace(throwableInformation));
      exceptionInformation.put("stacktrace", stackTrace);
    }
    logstashEvent.put("exception", exceptionInformation);
  }

  if (includeLocationInfo) {
    StackTraceElement info = loggingEvent.getSource();
    logstashEvent.put("file", info.getFileName());
    logstashEvent.put("line_number", info.getLineNumber());
    logstashEvent.put("class", info.getClassName());
    logstashEvent.put("method", info.getMethodName());
  }

  logstashEvent.put("logger_name", loggingEvent.getLoggerName());
  logstashEvent.put("mdc", mdc);
  logstashEvent.put("ndc", ndc);
  logstashEvent.put("level", loggingEvent.getLevel().toString());
  logstashEvent.put("thread_name", threadName);

  return logstashEvent;
}
 
Example 14
Source File: RelativeTimePatternConverter.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 long timestamp = event.getTimeMillis();
    toAppendTo.append(timestamp - startTime);
}