diff --git a/docs/core/logging.md b/docs/core/logging.md index 88cbb1be2..7589b9a03 100644 --- a/docs/core/logging.md +++ b/docs/core/logging.md @@ -1620,7 +1620,9 @@ Logback configuration is done in _logback.xml_ and the `LambdaJsonEncoder`: The `LambdaJsonEncoder` can be customized in different ways: #### Customising date format -Utility by default emits `timestamp` field in the logs in format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'` and in system default timezone. +Utility by default emits `timestamp` field in the logs in format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'` and in UTC, even when the JVM default timezone is different. +Explicitly setting `timestampFormat` without `timestampFormatTimezoneId` uses the system default timezone, even when the configured pattern matches the default. +An explicit `timestampFormatTimezoneId` takes precedence regardless of the order of the settings. If you need to customize format and timezone, you can change use the following: ```xml diff --git a/powertools-logging/powertools-logging-logback/src/main/java/software/amazon/lambda/powertools/logging/logback/LambdaJsonEncoder.java b/powertools-logging/powertools-logging-logback/src/main/java/software/amazon/lambda/powertools/logging/logback/LambdaJsonEncoder.java index 34807e8ee..015f25fb7 100644 --- a/powertools-logging/powertools-logging-logback/src/main/java/software/amazon/lambda/powertools/logging/logback/LambdaJsonEncoder.java +++ b/powertools-logging/powertools-logging-logback/src/main/java/software/amazon/lambda/powertools/logging/logback/LambdaJsonEncoder.java @@ -44,11 +44,13 @@ public class LambdaJsonEncoder extends EncoderBase { protected static final String EXCEPTION_CLASS_ATTR_NAME = "name"; protected static final String EXCEPTION_STACK_ATTR_NAME = "stack"; protected static final String EXCEPTION_ATTR_NAME = "error"; + private static final String DEFAULT_TIMESTAMP_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; private final ThrowableProxyConverter throwableProxyConverter = new ThrowableProxyConverter(); protected ThrowableHandlingConverter throwableConverter = null; - protected String timestampFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; + protected String timestampFormat = DEFAULT_TIMESTAMP_FORMAT; protected String timestampFormatTimezoneId = null; + private boolean timestampFormatConfigured = false; private boolean includeThreadInfo = false; private boolean includePowertoolsInfo = true; @@ -90,7 +92,7 @@ public byte[] encode(ILoggingEvent event) { serializer.writeRaw(','); serializeTimestamp(serializer, event.getTimeStamp(), - timestampFormat, timestampFormatTimezoneId, TIMESTAMP_ATTR_NAME); + timestampFormat, getTimestampTimezoneId(), TIMESTAMP_ATTR_NAME); serializer.writeEndObject(); serializer.writeRaw('\n'); @@ -100,6 +102,15 @@ public byte[] encode(ILoggingEvent event) { return builder.toString().getBytes(UTF_8); } + private String getTimestampTimezoneId() { + if (timestampFormatTimezoneId == null && !timestampFormatConfigured + && DEFAULT_TIMESTAMP_FORMAT.equals(timestampFormat)) { + // The built-in format has a literal UTC designator, not a timezone offset. + return "UTC"; + } + return timestampFormatTimezoneId; + } + private Map getKeyValuePairs(ILoggingEvent event) { return Optional.ofNullable(event.getKeyValuePairs()) .orElse(Collections.emptyList()).stream() @@ -157,6 +168,8 @@ public byte[] footerBytes() { /** * Specify the format of the timestamp (default is yyyy-MM-dd'T'HH:mm:ss.SSS'Z'). + * By default timestamps use UTC. Setting a format uses the system default timezone unless + * {@link #setTimestampFormatTimezoneId(String)} is also configured. * Note that if you use the Lambda Advanced Logging Configuration, you should keep the default format. *
*
{@code
@@ -169,10 +182,12 @@ public byte[] footerBytes() {
      */
     public void setTimestampFormat(String timestampFormat) {
         this.timestampFormat = timestampFormat;
+        this.timestampFormatConfigured = true;
     }
 
     /**
-     * Specify the format of the time zone id for timestamp (default is null, no timezone):
+     * Specify the time zone id for timestamp (default is null: UTC for the built-in format,
+     * or the system default timezone when a timestamp format is explicitly configured):
      * 
*
{@code
      *     
diff --git a/powertools-logging/powertools-logging-logback/src/test/java/software/amazon/lambda/powertools/logging/internal/LambdaJsonEncoderTimezoneTest.java b/powertools-logging/powertools-logging-logback/src/test/java/software/amazon/lambda/powertools/logging/internal/LambdaJsonEncoderTimezoneTest.java
new file mode 100644
index 000000000..3c0b4e1e1
--- /dev/null
+++ b/powertools-logging/powertools-logging-logback/src/test/java/software/amazon/lambda/powertools/logging/internal/LambdaJsonEncoderTimezoneTest.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright 2023 Amazon.com, Inc. or its affiliates.
+ * Licensed under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package software.amazon.lambda.powertools.logging.internal;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.spi.LoggingEvent;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.TimeZone;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.parallel.Isolated;
+import software.amazon.lambda.powertools.logging.logback.LambdaJsonEncoder;
+
+@Isolated("Changes the JVM default timezone")
+class LambdaJsonEncoderTimezoneTest {
+    private static final Instant EVENT_TIME = Instant.parse("2026-07-15T12:34:56.789Z");
+
+    @Test
+    void shouldEmitDefaultTimestampAtEventInstant() throws IOException {
+        LambdaJsonEncoder encoder = new LambdaJsonEncoder();
+        for (Instant instant : new Instant[] {EVENT_TIME, Instant.parse("2026-01-15T12:34:56.789Z")}) {
+            assertThat(Instant.parse(timestamp(encoder, instant))).isEqualTo(instant);
+        }
+    }
+
+    @Test
+    void shouldUseSystemTimeZoneForCustomFormat() throws IOException {
+        LambdaJsonEncoder encoder = new LambdaJsonEncoder();
+        encoder.setTimestampFormat("yyyy-MM-dd HH:mm:ss.SSS XXX");
+
+        assertThat(timestamp(encoder, EVENT_TIME)).isEqualTo("2026-07-15 08:34:56.789 -04:00");
+    }
+
+    @Test
+    void shouldPreserveExplicitDefaultPatternConfiguration() throws IOException {
+        LambdaJsonEncoder encoder = new LambdaJsonEncoder();
+        encoder.setTimestampFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
+
+        assertThat(timestamp(encoder, EVENT_TIME)).isEqualTo("2026-07-15T08:34:56.789Z");
+    }
+
+    @Test
+    void shouldHonorExplicitTimeZoneWithDefaultFormat() throws IOException {
+        LambdaJsonEncoder encoder = new LambdaJsonEncoder();
+        encoder.setTimestampFormatTimezoneId("Asia/Tokyo");
+
+        assertThat(timestamp(encoder, EVENT_TIME)).isEqualTo("2026-07-15T21:34:56.789Z");
+    }
+
+    @Test
+    void shouldHonorExplicitTimeZoneAfterFormat() throws IOException {
+        LambdaJsonEncoder encoder = new LambdaJsonEncoder();
+        encoder.setTimestampFormat("yyyy-MM-dd HH:mm:ss.SSS XXX");
+        encoder.setTimestampFormatTimezoneId("Asia/Tokyo");
+
+        assertThat(timestamp(encoder, EVENT_TIME)).isEqualTo("2026-07-15 21:34:56.789 +09:00");
+    }
+
+    @Test
+    void shouldHonorExplicitTimeZoneBeforeFormat() throws IOException {
+        LambdaJsonEncoder encoder = new LambdaJsonEncoder();
+        encoder.setTimestampFormatTimezoneId("Asia/Tokyo");
+        encoder.setTimestampFormat("yyyy-MM-dd HH:mm:ss.SSS XXX");
+
+        assertThat(timestamp(encoder, EVENT_TIME)).isEqualTo("2026-07-15 21:34:56.789 +09:00");
+    }
+
+    @Test
+    void shouldPreserveUnformattedTimestamp() throws IOException {
+        LambdaJsonEncoder encoder = new LambdaJsonEncoder();
+        encoder.setTimestampFormat(null);
+
+        assertThat(timestamp(encoder, EVENT_TIME)).isEqualTo(Long.toString(EVENT_TIME.toEpochMilli()));
+    }
+
+    private String timestamp(LambdaJsonEncoder encoder, Instant instant) throws IOException {
+        TimeZone originalTimeZone = TimeZone.getDefault();
+        try {
+            TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
+            LoggingEvent event = new LoggingEvent();
+            event.setLevel(Level.INFO);
+            event.setMessage("message");
+            event.setMDCPropertyMap(Collections.emptyMap());
+            event.setTimeStamp(instant.toEpochMilli());
+            return new ObjectMapper().readTree(encoder.encode(event)).get("timestamp").asText();
+        } finally {
+            TimeZone.setDefault(originalTimeZone);
+        }
+    }
+}