Skip to content

Commit ec95664

Browse files
committed
Logback appender: map timestamp in nanoseconds if possible (#11807)
1 parent 5ba1451 commit ec95664

File tree

1 file changed

+29
-2
lines changed
  • instrumentation/logback/logback-appender-1.0/library/src/main/java/io/opentelemetry/instrumentation/logback/appender/v1_0/internal

1 file changed

+29
-2
lines changed

instrumentation/logback/logback-appender-1.0/library/src/main/java/io/opentelemetry/instrumentation/logback/appender/v1_0/internal/LoggingEventMapper.java

+29-2
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ public final class LoggingEventMapper {
4545
private static final AttributeKey<Long> THREAD_ID = AttributeKey.longKey("thread.id");
4646
private static final AttributeKey<String> THREAD_NAME = AttributeKey.stringKey("thread.name");
4747

48+
private static final boolean supportsInstant = supportsInstant();
4849
private static final boolean supportsKeyValuePairs = supportsKeyValuePairs();
4950
private static final boolean supportsMultipleMarkers = supportsMultipleMarkers();
5051
private static final Cache<String, AttributeKey<String>> mdcAttributeKeys = Cache.bounded(100);
@@ -106,8 +107,12 @@ private void mapLoggingEvent(
106107
}
107108

108109
// time
109-
long timestamp = loggingEvent.getTimeStamp();
110-
builder.setTimestamp(timestamp, TimeUnit.MILLISECONDS);
110+
if (supportsInstant && hasInstant(loggingEvent)) {
111+
setTimestampFromInstant(builder, loggingEvent);
112+
} else {
113+
long timestamp = loggingEvent.getTimeStamp();
114+
builder.setTimestamp(timestamp, TimeUnit.MILLISECONDS);
115+
}
111116

112117
// level
113118
Level level = loggingEvent.getLevel();
@@ -174,6 +179,28 @@ private void mapLoggingEvent(
174179
builder.setContext(Context.current());
175180
}
176181

182+
// getInstant is available since Logback 1.3
183+
private static boolean supportsInstant() {
184+
try {
185+
ILoggingEvent.class.getMethod("getInstant");
186+
} catch (NoSuchMethodException e) {
187+
return false;
188+
}
189+
190+
return true;
191+
}
192+
193+
@NoMuzzle
194+
private static boolean hasInstant(ILoggingEvent loggingEvent) {
195+
return loggingEvent.getInstant() != null;
196+
}
197+
198+
@NoMuzzle
199+
private static void setTimestampFromInstant(
200+
LogRecordBuilder builder, ILoggingEvent loggingEvent) {
201+
builder.setTimestamp(loggingEvent.getInstant());
202+
}
203+
177204
// visible for testing
178205
void captureMdcAttributes(AttributesBuilder attributes, Map<String, String> mdcProperties) {
179206
if (captureAllMdcAttributes) {

0 commit comments

Comments
 (0)