diff --git a/spring-cloud-gcp-logging/src/main/java/com/google/cloud/spring/logging/StackdriverJsonLayout.java b/spring-cloud-gcp-logging/src/main/java/com/google/cloud/spring/logging/StackdriverJsonLayout.java index 1ba2cc04f2..ba6f04aea8 100644 --- a/spring-cloud-gcp-logging/src/main/java/com/google/cloud/spring/logging/StackdriverJsonLayout.java +++ b/spring-cloud-gcp-logging/src/main/java/com/google/cloud/spring/logging/StackdriverJsonLayout.java @@ -271,9 +271,10 @@ protected Map toJsonMap(ILoggingEvent event) { map.put( StackdriverTraceConstants.TIMESTAMP_SECONDS_ATTRIBUTE, TimeUnit.MILLISECONDS.toSeconds(event.getTimeStamp())); + int nanoseconds = event.getNanoseconds(); map.put( StackdriverTraceConstants.TIMESTAMP_NANOS_ATTRIBUTE, - TimeUnit.MILLISECONDS.toNanos(event.getTimeStamp() % 1_000)); + nanoseconds != -1 ? nanoseconds : TimeUnit.MILLISECONDS.toNanos(event.getTimeStamp() % 1_000)); } add( diff --git a/spring-cloud-gcp-logging/src/test/java/com/google/cloud/spring/logging/StackdriverJsonLayoutLoggerTests.java b/spring-cloud-gcp-logging/src/test/java/com/google/cloud/spring/logging/StackdriverJsonLayoutLoggerTests.java index 625f9b245a..7e06a330bc 100644 --- a/spring-cloud-gcp-logging/src/test/java/com/google/cloud/spring/logging/StackdriverJsonLayoutLoggerTests.java +++ b/spring-cloud-gcp-logging/src/test/java/com/google/cloud/spring/logging/StackdriverJsonLayoutLoggerTests.java @@ -246,6 +246,23 @@ void testJsonSeverityLevelMapping() { .containsExactly("DEBUG", "DEBUG", "INFO", "WARNING", "ERROR", "ERROR"); } + @Test + void testTimestampNanos() { + LOGGER.warn("test1"); + LOGGER.warn("test2"); + + List jsonLogRecords = Arrays.asList(new String(logOutput.toByteArray()).split("\n")); + + List logTimestampNanos = + jsonLogRecords.stream() + .map(record -> GSON.fromJson(record, Map.class)) + .map(data -> (Double) data.get(StackdriverTraceConstants.TIMESTAMP_NANOS_ATTRIBUTE)) + .collect(Collectors.toList()); + + assertThat(logTimestampNanos).hasSize(2); + assertThat(logTimestampNanos).anySatisfy(nanos -> assertThat(nanos % 1000000).isPositive()); + } + @Test void testJsonLayoutEnhancer_missing() { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();