From 2a4c14ab43b99c80879d94779bde943bd3e3ba78 Mon Sep 17 00:00:00 2001 From: Raf0 Date: Mon, 10 Jul 2023 16:53:46 +0200 Subject: [PATCH] fix: timestampNanos field with nanos precision (#2012) Fixes: #1996 --- .../spring/logging/StackdriverJsonLayout.java | 3 ++- .../StackdriverJsonLayoutLoggerTests.java | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) 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();