Skip to content

Logback appender: map timestamp in nanoseconds if possible (#11807) #11974

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading