Skip to content

Commit

Permalink
Logback appender: map timestamp in nanoseconds if possible (#11807) (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
jjoslet authored Aug 14, 2024
1 parent 31e5eea commit dee515d
Showing 1 changed file with 29 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ public final class LoggingEventMapper {
private static final AttributeKey<Long> THREAD_ID = AttributeKey.longKey("thread.id");
private static final AttributeKey<String> THREAD_NAME = AttributeKey.stringKey("thread.name");

private static final boolean supportsInstant = supportsInstant();
private static final boolean supportsKeyValuePairs = supportsKeyValuePairs();
private static final boolean supportsMultipleMarkers = supportsMultipleMarkers();
private static final Cache<String, AttributeKey<String>> mdcAttributeKeys = Cache.bounded(100);
Expand Down Expand Up @@ -106,8 +107,12 @@ private void mapLoggingEvent(
}

// time
long timestamp = loggingEvent.getTimeStamp();
builder.setTimestamp(timestamp, TimeUnit.MILLISECONDS);
if (supportsInstant && hasInstant(loggingEvent)) {
setTimestampFromInstant(builder, loggingEvent);
} else {
long timestamp = loggingEvent.getTimeStamp();
builder.setTimestamp(timestamp, TimeUnit.MILLISECONDS);
}

// level
Level level = loggingEvent.getLevel();
Expand Down Expand Up @@ -174,6 +179,28 @@ private void mapLoggingEvent(
builder.setContext(Context.current());
}

// getInstant is available since Logback 1.3
private static boolean supportsInstant() {
try {
ILoggingEvent.class.getMethod("getInstant");
} catch (NoSuchMethodException e) {
return false;
}

return true;
}

@NoMuzzle
private static boolean hasInstant(ILoggingEvent loggingEvent) {
return loggingEvent.getInstant() != null;
}

@NoMuzzle
private static void setTimestampFromInstant(
LogRecordBuilder builder, ILoggingEvent loggingEvent) {
builder.setTimestamp(loggingEvent.getInstant());
}

// visible for testing
void captureMdcAttributes(AttributesBuilder attributes, Map<String, String> mdcProperties) {
if (captureAllMdcAttributes) {
Expand Down

0 comments on commit dee515d

Please sign in to comment.