You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@logging.apache.org by GitBox <gi...@apache.org> on 2021/07/19 21:31:04 UTC

[GitHub] [logging-log4j2] vy opened a new pull request #551: LOG4J2-3116 Add GCP logging layout

vy opened a new pull request #551:
URL: https://github.com/apache/logging-log4j2/pull/551


   This PR aims to supersede #543.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@logging.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [logging-log4j2] vy closed pull request #551: LOG4J2-3116 Add GCP logging layout

Posted by GitBox <gi...@apache.org>.
vy closed pull request #551:
URL: https://github.com/apache/logging-log4j2/pull/551


   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@logging.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [logging-log4j2] vy commented on a change in pull request #551: LOG4J2-3116 Add GCP logging layout

Posted by GitBox <gi...@apache.org>.
vy commented on a change in pull request #551:
URL: https://github.com/apache/logging-log4j2/pull/551#discussion_r672678885



##########
File path: log4j-layout-template-json/src/main/resources/GcpLayout.json
##########
@@ -0,0 +1,67 @@
+{
+  "timestamp": {
+    "$resolver": "timestamp",
+    "pattern": {
+      "format": "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
+      "timeZone": "UTC",
+      "locale": "en_US"
+    }
+  },
+  "severity": {
+    "$resolver": "pattern",
+    "pattern": "%level{WARN=WARNING, TRACE=DEBUG, FATAL=EMERGENCY}",
+    "stackTraceEnabled": false
+  },
+  "message": {
+    "$resolver": "pattern",
+    "pattern": "%m"

Review comment:
       Good catch! Will do.

##########
File path: log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/GcpLayoutTest.java
##########
@@ -0,0 +1,221 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.logging.log4j.layout.template.json;
+
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.core.LogEvent;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintWriter;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.Locale;
+import java.util.stream.Stream;
+
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.CONFIGURATION;
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.usingSerializedLogEventAccessor;
+import static org.assertj.core.api.Assertions.assertThat;
+
+class GcpLayoutTest {
+
+    private static final JsonTemplateLayout LAYOUT = JsonTemplateLayout
+            .newBuilder()
+            .setConfiguration(CONFIGURATION)
+            .setStackTraceEnabled(true)
+            .setLocationInfoEnabled(true)
+            .setEventTemplateUri("classpath:GcpLayout.json")
+            .build();
+
+    private static final int LOG_EVENT_COUNT = 1_000;
+
+    private static final DateTimeFormatter DATE_TIME_FORMATTER =
+            DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
+
+    @ParameterizedTest
+    @MethodSource("createLiteLogEvents")
+    void test_lite_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_lite_log_events()
+    private static Stream<Arguments> createLiteLogEvents() {
+        return LogEventFixture
+                .createLiteLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    @ParameterizedTest
+    @MethodSource("createFullLogEvents")
+    void test_full_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_full_log_events()
+    private static Stream<Arguments> createFullLogEvents() {
+        return LogEventFixture
+                .createFullLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    void verifySerialization(final LogEvent logEvent) {
+        usingSerializedLogEventAccessor(LAYOUT, logEvent, accessor -> {
+
+            // Verify timestamp.
+            final String expectedTimestamp = formatLogEventInstant(logEvent);
+            assertThat(accessor.getString("timestamp")).isEqualTo(expectedTimestamp);
+
+            // Verify severity.
+            final Level level = logEvent.getLevel();
+            final String expectedSeverity;
+            if (Level.WARN.equals(level)) {
+                expectedSeverity = "WARNING";
+            } else if (Level.TRACE.equals(level)) {
+                expectedSeverity = "TRACE";
+            } else if (Level.FATAL.equals(level)) {
+                expectedSeverity = "EMERGENCY";
+            } else {
+                expectedSeverity = level.name();
+            }
+            assertThat(accessor.getString("severity")).isEqualTo(expectedSeverity);
+
+            // Verify message.
+            final String expectedMessage = logEvent.getMessage().getFormattedMessage();
+            assertThat(accessor.getString("message")).contains(expectedMessage);
+            final Throwable exception = logEvent.getThrown();
+            if (exception != null) {
+                final String expectedExceptionMessage = exception.getLocalizedMessage();
+                assertThat(accessor.getString("message")).contains(expectedExceptionMessage);

Review comment:
       Was working on this and... It has turned out to be pretty difficult. `PatternLayout`s `ExtendedThrowablePatternConverter` uses `ThrowableProxy`, which has a pretty different way of working than `JsonTemplateLayout`s `StackTraceStringResolver`. In order to make `message` and `_exception.stackTrace` match, I needed to make the latter use `%xEx` pattern too. Yet, I still could not succeed in reproducing the `PatternLayout`-serialized stack trace in tests. I will continue working on this tomorrow.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@logging.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [logging-log4j2] vy closed pull request #551: LOG4J2-3116 Add GCP logging layout

Posted by GitBox <gi...@apache.org>.
vy closed pull request #551:
URL: https://github.com/apache/logging-log4j2/pull/551


   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@logging.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [logging-log4j2] rocketraman commented on a change in pull request #551: LOG4J2-3116 Add GCP logging layout

Posted by GitBox <gi...@apache.org>.
rocketraman commented on a change in pull request #551:
URL: https://github.com/apache/logging-log4j2/pull/551#discussion_r672657984



##########
File path: log4j-layout-template-json/src/main/resources/GcpLayout.json
##########
@@ -0,0 +1,67 @@
+{
+  "timestamp": {
+    "$resolver": "timestamp",
+    "pattern": {
+      "format": "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
+      "timeZone": "UTC",
+      "locale": "en_US"
+    }
+  },
+  "severity": {
+    "$resolver": "pattern",
+    "pattern": "%level{WARN=WARNING, TRACE=DEBUG, FATAL=EMERGENCY}",
+    "stackTraceEnabled": false
+  },
+  "message": {
+    "$resolver": "pattern",
+    "pattern": "%m"

Review comment:
       I see you removed `stackTraceEnabled` setting here. I believe stackTraceEnabled defaults to `true` so that has no practical impact, but because Google's documentation is clear that the stack trace should be added to the `message` field, I felt that explicitly adding that attribute here was a useful hint / recognition of the explicit design of this layout.

##########
File path: log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/GcpLayoutTest.java
##########
@@ -0,0 +1,221 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.logging.log4j.layout.template.json;
+
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.core.LogEvent;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintWriter;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.Locale;
+import java.util.stream.Stream;
+
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.CONFIGURATION;
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.usingSerializedLogEventAccessor;
+import static org.assertj.core.api.Assertions.assertThat;
+
+class GcpLayoutTest {
+
+    private static final JsonTemplateLayout LAYOUT = JsonTemplateLayout
+            .newBuilder()
+            .setConfiguration(CONFIGURATION)
+            .setStackTraceEnabled(true)
+            .setLocationInfoEnabled(true)
+            .setEventTemplateUri("classpath:GcpLayout.json")
+            .build();
+
+    private static final int LOG_EVENT_COUNT = 1_000;
+
+    private static final DateTimeFormatter DATE_TIME_FORMATTER =
+            DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
+
+    @ParameterizedTest
+    @MethodSource("createLiteLogEvents")
+    void test_lite_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_lite_log_events()
+    private static Stream<Arguments> createLiteLogEvents() {
+        return LogEventFixture
+                .createLiteLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    @ParameterizedTest
+    @MethodSource("createFullLogEvents")
+    void test_full_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_full_log_events()
+    private static Stream<Arguments> createFullLogEvents() {
+        return LogEventFixture
+                .createFullLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    void verifySerialization(final LogEvent logEvent) {
+        usingSerializedLogEventAccessor(LAYOUT, logEvent, accessor -> {
+
+            // Verify timestamp.
+            final String expectedTimestamp = formatLogEventInstant(logEvent);
+            assertThat(accessor.getString("timestamp")).isEqualTo(expectedTimestamp);
+
+            // Verify severity.
+            final Level level = logEvent.getLevel();
+            final String expectedSeverity;
+            if (Level.WARN.equals(level)) {
+                expectedSeverity = "WARNING";
+            } else if (Level.TRACE.equals(level)) {
+                expectedSeverity = "TRACE";
+            } else if (Level.FATAL.equals(level)) {
+                expectedSeverity = "EMERGENCY";
+            } else {
+                expectedSeverity = level.name();
+            }
+            assertThat(accessor.getString("severity")).isEqualTo(expectedSeverity);
+
+            // Verify message.
+            final String expectedMessage = logEvent.getMessage().getFormattedMessage();
+            assertThat(accessor.getString("message")).contains(expectedMessage);
+            final Throwable exception = logEvent.getThrown();
+            if (exception != null) {
+                final String expectedExceptionMessage = exception.getLocalizedMessage();
+                assertThat(accessor.getString("message")).contains(expectedExceptionMessage);
+            }
+
+            // Verify labels.
+            logEvent.getContextData().forEach((key, value) -> {
+                final String expectedValue = String.valueOf(value);
+                final String actualValue =
+                        accessor.getString(new String[]{
+                                "logging.googleapis.com/labels", key});
+                assertThat(actualValue).isEqualTo(expectedValue);
+            });
+
+            final StackTraceElement source = logEvent.getSource();
+            if (source != null) {
+
+                // Verify file name.
+                final String actualFileName =
+                        accessor.getString(new String[]{
+                        "logging.googleapis.com/sourceLocation", "file"});
+                assertThat(actualFileName).isEqualTo(source.getFileName());
+
+                // Verify line number.
+                final int actualLineNumber =
+                        accessor.getInteger(new String[]{
+                                "logging.googleapis.com/sourceLocation", "line"});
+                assertThat(actualLineNumber).isEqualTo(source.getLineNumber());
+
+                // Verify function.
+                final String expectedFunction =
+                        source.getClassName() + "." + source.getMethodName();
+                final String actualFunction =
+                        accessor.getString(new String[]{
+                                "logging.googleapis.com/sourceLocation", "function"});
+                assertThat(actualFunction).isEqualTo(expectedFunction);
+
+            } else {
+                assertThat(accessor.exists(
+                        new String[]{"logging.googleapis.com/sourceLocation", "file"}))
+                        .isFalse();
+                assertThat(accessor.exists(
+                        new String[]{"logging.googleapis.com/sourceLocation", "line"}))
+                        .isFalse();
+                assertThat(accessor.getString(
+                        new String[]{"logging.googleapis.com/sourceLocation", "function"}))
+                        .isEmpty();
+            }
+
+            // Verify insert id.
+            assertThat(accessor.getString("logging.googleapis.com/insertId"))
+                    .matches("[-]?[0-9]+");
+
+            // Verify exception.
+            if (exception != null) {
+
+                // Verify exception class.
+                assertThat(accessor.getString(
+                        new String[]{"_exception", "class"}))
+                        .isEqualTo(exception.getClass().getCanonicalName());
+
+                // Verify exception message.
+                assertThat(accessor.getString(
+                        new String[]{"_exception", "message"}))
+                        .isEqualTo(exception.getMessage());
+
+                // Verify exception stack trace.
+                final String expectedExceptionStackTrace =
+                        serializeThrowableStackTrace(exception);
+                assertThat(accessor.getString(
+                        new String[]{"_exception", "stackTrace"}))
+                        .isEqualTo(expectedExceptionStackTrace);
+
+            } else {
+                assertThat(accessor.getObject(
+                        new String[]{"_exception", "class"}))
+                        .isNull();
+                assertThat(accessor.getObject(
+                        new String[]{"_exception", "message"}))
+                        .isNull();
+                assertThat(accessor.getObject(
+                        new String[]{"_exception", "stackTrace"}))
+                        .isNull();
+            }
+
+            // Verify thread name.
+            assertThat(accessor.getString("_thread"))
+                    .isEqualTo(logEvent.getThreadName());
+
+            // Verify logger name.
+            assertThat(accessor.getString("_logger"))
+                    .isEqualTo(logEvent.getLoggerName());
+
+        });

Review comment:
       Much better than my version of the test, thanks. I think I got off on the wrong foot by using Ecs and Gelf layout tests as a starting point.

##########
File path: log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/GcpLayoutTest.java
##########
@@ -0,0 +1,221 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.logging.log4j.layout.template.json;
+
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.core.LogEvent;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintWriter;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.Locale;
+import java.util.stream.Stream;
+
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.CONFIGURATION;
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.usingSerializedLogEventAccessor;
+import static org.assertj.core.api.Assertions.assertThat;
+
+class GcpLayoutTest {
+
+    private static final JsonTemplateLayout LAYOUT = JsonTemplateLayout
+            .newBuilder()
+            .setConfiguration(CONFIGURATION)
+            .setStackTraceEnabled(true)
+            .setLocationInfoEnabled(true)
+            .setEventTemplateUri("classpath:GcpLayout.json")
+            .build();
+
+    private static final int LOG_EVENT_COUNT = 1_000;
+
+    private static final DateTimeFormatter DATE_TIME_FORMATTER =
+            DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
+
+    @ParameterizedTest
+    @MethodSource("createLiteLogEvents")
+    void test_lite_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_lite_log_events()
+    private static Stream<Arguments> createLiteLogEvents() {
+        return LogEventFixture
+                .createLiteLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    @ParameterizedTest
+    @MethodSource("createFullLogEvents")
+    void test_full_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_full_log_events()
+    private static Stream<Arguments> createFullLogEvents() {
+        return LogEventFixture
+                .createFullLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    void verifySerialization(final LogEvent logEvent) {
+        usingSerializedLogEventAccessor(LAYOUT, logEvent, accessor -> {
+
+            // Verify timestamp.
+            final String expectedTimestamp = formatLogEventInstant(logEvent);
+            assertThat(accessor.getString("timestamp")).isEqualTo(expectedTimestamp);
+
+            // Verify severity.
+            final Level level = logEvent.getLevel();
+            final String expectedSeverity;
+            if (Level.WARN.equals(level)) {
+                expectedSeverity = "WARNING";
+            } else if (Level.TRACE.equals(level)) {
+                expectedSeverity = "TRACE";
+            } else if (Level.FATAL.equals(level)) {
+                expectedSeverity = "EMERGENCY";
+            } else {
+                expectedSeverity = level.name();
+            }
+            assertThat(accessor.getString("severity")).isEqualTo(expectedSeverity);
+
+            // Verify message.
+            final String expectedMessage = logEvent.getMessage().getFormattedMessage();
+            assertThat(accessor.getString("message")).contains(expectedMessage);
+            final Throwable exception = logEvent.getThrown();
+            if (exception != null) {
+                final String expectedExceptionMessage = exception.getLocalizedMessage();
+                assertThat(accessor.getString("message")).contains(expectedExceptionMessage);

Review comment:
       Can we add a test for the stack trace being in the message? This just tests the exception message.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@logging.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [logging-log4j2] rocketraman commented on a change in pull request #551: LOG4J2-3116 Add GCP logging layout

Posted by GitBox <gi...@apache.org>.
rocketraman commented on a change in pull request #551:
URL: https://github.com/apache/logging-log4j2/pull/551#discussion_r672657984



##########
File path: log4j-layout-template-json/src/main/resources/GcpLayout.json
##########
@@ -0,0 +1,67 @@
+{
+  "timestamp": {
+    "$resolver": "timestamp",
+    "pattern": {
+      "format": "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
+      "timeZone": "UTC",
+      "locale": "en_US"
+    }
+  },
+  "severity": {
+    "$resolver": "pattern",
+    "pattern": "%level{WARN=WARNING, TRACE=DEBUG, FATAL=EMERGENCY}",
+    "stackTraceEnabled": false
+  },
+  "message": {
+    "$resolver": "pattern",
+    "pattern": "%m"

Review comment:
       I see you removed `stackTraceEnabled` setting here. I believe stackTraceEnabled defaults to `true` so that has no practical impact, but because Google's documentation is clear that the stack trace should be added to the `message` field, I felt that explicitly adding that attribute here was a useful hint / recognition of the explicit design of this layout.

##########
File path: log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/GcpLayoutTest.java
##########
@@ -0,0 +1,221 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.logging.log4j.layout.template.json;
+
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.core.LogEvent;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintWriter;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.Locale;
+import java.util.stream.Stream;
+
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.CONFIGURATION;
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.usingSerializedLogEventAccessor;
+import static org.assertj.core.api.Assertions.assertThat;
+
+class GcpLayoutTest {
+
+    private static final JsonTemplateLayout LAYOUT = JsonTemplateLayout
+            .newBuilder()
+            .setConfiguration(CONFIGURATION)
+            .setStackTraceEnabled(true)
+            .setLocationInfoEnabled(true)
+            .setEventTemplateUri("classpath:GcpLayout.json")
+            .build();
+
+    private static final int LOG_EVENT_COUNT = 1_000;
+
+    private static final DateTimeFormatter DATE_TIME_FORMATTER =
+            DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
+
+    @ParameterizedTest
+    @MethodSource("createLiteLogEvents")
+    void test_lite_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_lite_log_events()
+    private static Stream<Arguments> createLiteLogEvents() {
+        return LogEventFixture
+                .createLiteLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    @ParameterizedTest
+    @MethodSource("createFullLogEvents")
+    void test_full_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_full_log_events()
+    private static Stream<Arguments> createFullLogEvents() {
+        return LogEventFixture
+                .createFullLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    void verifySerialization(final LogEvent logEvent) {
+        usingSerializedLogEventAccessor(LAYOUT, logEvent, accessor -> {
+
+            // Verify timestamp.
+            final String expectedTimestamp = formatLogEventInstant(logEvent);
+            assertThat(accessor.getString("timestamp")).isEqualTo(expectedTimestamp);
+
+            // Verify severity.
+            final Level level = logEvent.getLevel();
+            final String expectedSeverity;
+            if (Level.WARN.equals(level)) {
+                expectedSeverity = "WARNING";
+            } else if (Level.TRACE.equals(level)) {
+                expectedSeverity = "TRACE";
+            } else if (Level.FATAL.equals(level)) {
+                expectedSeverity = "EMERGENCY";
+            } else {
+                expectedSeverity = level.name();
+            }
+            assertThat(accessor.getString("severity")).isEqualTo(expectedSeverity);
+
+            // Verify message.
+            final String expectedMessage = logEvent.getMessage().getFormattedMessage();
+            assertThat(accessor.getString("message")).contains(expectedMessage);
+            final Throwable exception = logEvent.getThrown();
+            if (exception != null) {
+                final String expectedExceptionMessage = exception.getLocalizedMessage();
+                assertThat(accessor.getString("message")).contains(expectedExceptionMessage);
+            }
+
+            // Verify labels.
+            logEvent.getContextData().forEach((key, value) -> {
+                final String expectedValue = String.valueOf(value);
+                final String actualValue =
+                        accessor.getString(new String[]{
+                                "logging.googleapis.com/labels", key});
+                assertThat(actualValue).isEqualTo(expectedValue);
+            });
+
+            final StackTraceElement source = logEvent.getSource();
+            if (source != null) {
+
+                // Verify file name.
+                final String actualFileName =
+                        accessor.getString(new String[]{
+                        "logging.googleapis.com/sourceLocation", "file"});
+                assertThat(actualFileName).isEqualTo(source.getFileName());
+
+                // Verify line number.
+                final int actualLineNumber =
+                        accessor.getInteger(new String[]{
+                                "logging.googleapis.com/sourceLocation", "line"});
+                assertThat(actualLineNumber).isEqualTo(source.getLineNumber());
+
+                // Verify function.
+                final String expectedFunction =
+                        source.getClassName() + "." + source.getMethodName();
+                final String actualFunction =
+                        accessor.getString(new String[]{
+                                "logging.googleapis.com/sourceLocation", "function"});
+                assertThat(actualFunction).isEqualTo(expectedFunction);
+
+            } else {
+                assertThat(accessor.exists(
+                        new String[]{"logging.googleapis.com/sourceLocation", "file"}))
+                        .isFalse();
+                assertThat(accessor.exists(
+                        new String[]{"logging.googleapis.com/sourceLocation", "line"}))
+                        .isFalse();
+                assertThat(accessor.getString(
+                        new String[]{"logging.googleapis.com/sourceLocation", "function"}))
+                        .isEmpty();
+            }
+
+            // Verify insert id.
+            assertThat(accessor.getString("logging.googleapis.com/insertId"))
+                    .matches("[-]?[0-9]+");
+
+            // Verify exception.
+            if (exception != null) {
+
+                // Verify exception class.
+                assertThat(accessor.getString(
+                        new String[]{"_exception", "class"}))
+                        .isEqualTo(exception.getClass().getCanonicalName());
+
+                // Verify exception message.
+                assertThat(accessor.getString(
+                        new String[]{"_exception", "message"}))
+                        .isEqualTo(exception.getMessage());
+
+                // Verify exception stack trace.
+                final String expectedExceptionStackTrace =
+                        serializeThrowableStackTrace(exception);
+                assertThat(accessor.getString(
+                        new String[]{"_exception", "stackTrace"}))
+                        .isEqualTo(expectedExceptionStackTrace);
+
+            } else {
+                assertThat(accessor.getObject(
+                        new String[]{"_exception", "class"}))
+                        .isNull();
+                assertThat(accessor.getObject(
+                        new String[]{"_exception", "message"}))
+                        .isNull();
+                assertThat(accessor.getObject(
+                        new String[]{"_exception", "stackTrace"}))
+                        .isNull();
+            }
+
+            // Verify thread name.
+            assertThat(accessor.getString("_thread"))
+                    .isEqualTo(logEvent.getThreadName());
+
+            // Verify logger name.
+            assertThat(accessor.getString("_logger"))
+                    .isEqualTo(logEvent.getLoggerName());
+
+        });

Review comment:
       Much better than my version of the test, thanks. I think I got off on the wrong foot by using Ecs and Gelf layout tests as a starting point.

##########
File path: log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/GcpLayoutTest.java
##########
@@ -0,0 +1,221 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.logging.log4j.layout.template.json;
+
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.core.LogEvent;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintWriter;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.Locale;
+import java.util.stream.Stream;
+
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.CONFIGURATION;
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.usingSerializedLogEventAccessor;
+import static org.assertj.core.api.Assertions.assertThat;
+
+class GcpLayoutTest {
+
+    private static final JsonTemplateLayout LAYOUT = JsonTemplateLayout
+            .newBuilder()
+            .setConfiguration(CONFIGURATION)
+            .setStackTraceEnabled(true)
+            .setLocationInfoEnabled(true)
+            .setEventTemplateUri("classpath:GcpLayout.json")
+            .build();
+
+    private static final int LOG_EVENT_COUNT = 1_000;
+
+    private static final DateTimeFormatter DATE_TIME_FORMATTER =
+            DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
+
+    @ParameterizedTest
+    @MethodSource("createLiteLogEvents")
+    void test_lite_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_lite_log_events()
+    private static Stream<Arguments> createLiteLogEvents() {
+        return LogEventFixture
+                .createLiteLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    @ParameterizedTest
+    @MethodSource("createFullLogEvents")
+    void test_full_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_full_log_events()
+    private static Stream<Arguments> createFullLogEvents() {
+        return LogEventFixture
+                .createFullLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    void verifySerialization(final LogEvent logEvent) {
+        usingSerializedLogEventAccessor(LAYOUT, logEvent, accessor -> {
+
+            // Verify timestamp.
+            final String expectedTimestamp = formatLogEventInstant(logEvent);
+            assertThat(accessor.getString("timestamp")).isEqualTo(expectedTimestamp);
+
+            // Verify severity.
+            final Level level = logEvent.getLevel();
+            final String expectedSeverity;
+            if (Level.WARN.equals(level)) {
+                expectedSeverity = "WARNING";
+            } else if (Level.TRACE.equals(level)) {
+                expectedSeverity = "TRACE";
+            } else if (Level.FATAL.equals(level)) {
+                expectedSeverity = "EMERGENCY";
+            } else {
+                expectedSeverity = level.name();
+            }
+            assertThat(accessor.getString("severity")).isEqualTo(expectedSeverity);
+
+            // Verify message.
+            final String expectedMessage = logEvent.getMessage().getFormattedMessage();
+            assertThat(accessor.getString("message")).contains(expectedMessage);
+            final Throwable exception = logEvent.getThrown();
+            if (exception != null) {
+                final String expectedExceptionMessage = exception.getLocalizedMessage();
+                assertThat(accessor.getString("message")).contains(expectedExceptionMessage);

Review comment:
       Can we add a test for the stack trace being in the message? This just tests the exception message.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@logging.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [logging-log4j2] vy commented on a change in pull request #551: LOG4J2-3116 Add GCP logging layout

Posted by GitBox <gi...@apache.org>.
vy commented on a change in pull request #551:
URL: https://github.com/apache/logging-log4j2/pull/551#discussion_r672678885



##########
File path: log4j-layout-template-json/src/main/resources/GcpLayout.json
##########
@@ -0,0 +1,67 @@
+{
+  "timestamp": {
+    "$resolver": "timestamp",
+    "pattern": {
+      "format": "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
+      "timeZone": "UTC",
+      "locale": "en_US"
+    }
+  },
+  "severity": {
+    "$resolver": "pattern",
+    "pattern": "%level{WARN=WARNING, TRACE=DEBUG, FATAL=EMERGENCY}",
+    "stackTraceEnabled": false
+  },
+  "message": {
+    "$resolver": "pattern",
+    "pattern": "%m"

Review comment:
       Good catch! Will do.

##########
File path: log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/GcpLayoutTest.java
##########
@@ -0,0 +1,221 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.logging.log4j.layout.template.json;
+
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.core.LogEvent;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintWriter;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.Locale;
+import java.util.stream.Stream;
+
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.CONFIGURATION;
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.usingSerializedLogEventAccessor;
+import static org.assertj.core.api.Assertions.assertThat;
+
+class GcpLayoutTest {
+
+    private static final JsonTemplateLayout LAYOUT = JsonTemplateLayout
+            .newBuilder()
+            .setConfiguration(CONFIGURATION)
+            .setStackTraceEnabled(true)
+            .setLocationInfoEnabled(true)
+            .setEventTemplateUri("classpath:GcpLayout.json")
+            .build();
+
+    private static final int LOG_EVENT_COUNT = 1_000;
+
+    private static final DateTimeFormatter DATE_TIME_FORMATTER =
+            DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
+
+    @ParameterizedTest
+    @MethodSource("createLiteLogEvents")
+    void test_lite_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_lite_log_events()
+    private static Stream<Arguments> createLiteLogEvents() {
+        return LogEventFixture
+                .createLiteLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    @ParameterizedTest
+    @MethodSource("createFullLogEvents")
+    void test_full_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_full_log_events()
+    private static Stream<Arguments> createFullLogEvents() {
+        return LogEventFixture
+                .createFullLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    void verifySerialization(final LogEvent logEvent) {
+        usingSerializedLogEventAccessor(LAYOUT, logEvent, accessor -> {
+
+            // Verify timestamp.
+            final String expectedTimestamp = formatLogEventInstant(logEvent);
+            assertThat(accessor.getString("timestamp")).isEqualTo(expectedTimestamp);
+
+            // Verify severity.
+            final Level level = logEvent.getLevel();
+            final String expectedSeverity;
+            if (Level.WARN.equals(level)) {
+                expectedSeverity = "WARNING";
+            } else if (Level.TRACE.equals(level)) {
+                expectedSeverity = "TRACE";
+            } else if (Level.FATAL.equals(level)) {
+                expectedSeverity = "EMERGENCY";
+            } else {
+                expectedSeverity = level.name();
+            }
+            assertThat(accessor.getString("severity")).isEqualTo(expectedSeverity);
+
+            // Verify message.
+            final String expectedMessage = logEvent.getMessage().getFormattedMessage();
+            assertThat(accessor.getString("message")).contains(expectedMessage);
+            final Throwable exception = logEvent.getThrown();
+            if (exception != null) {
+                final String expectedExceptionMessage = exception.getLocalizedMessage();
+                assertThat(accessor.getString("message")).contains(expectedExceptionMessage);

Review comment:
       Was working on this and... It has turned out to be pretty difficult. `PatternLayout`s `ExtendedThrowablePatternConverter` uses `ThrowableProxy`, which has a pretty different way of working than `JsonTemplateLayout`s `StackTraceStringResolver`. In order to make `message` and `_exception.stackTrace` match, I needed to make the latter use `%xEx` pattern too. Yet, I still could not succeed in reproducing the `PatternLayout`-serialized stack trace in tests. I will continue working on this tomorrow.

##########
File path: log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/GcpLayoutTest.java
##########
@@ -0,0 +1,221 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.logging.log4j.layout.template.json;
+
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.core.LogEvent;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintWriter;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.Locale;
+import java.util.stream.Stream;
+
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.CONFIGURATION;
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.usingSerializedLogEventAccessor;
+import static org.assertj.core.api.Assertions.assertThat;
+
+class GcpLayoutTest {
+
+    private static final JsonTemplateLayout LAYOUT = JsonTemplateLayout
+            .newBuilder()
+            .setConfiguration(CONFIGURATION)
+            .setStackTraceEnabled(true)
+            .setLocationInfoEnabled(true)
+            .setEventTemplateUri("classpath:GcpLayout.json")
+            .build();
+
+    private static final int LOG_EVENT_COUNT = 1_000;
+
+    private static final DateTimeFormatter DATE_TIME_FORMATTER =
+            DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
+
+    @ParameterizedTest
+    @MethodSource("createLiteLogEvents")
+    void test_lite_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_lite_log_events()
+    private static Stream<Arguments> createLiteLogEvents() {
+        return LogEventFixture
+                .createLiteLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    @ParameterizedTest
+    @MethodSource("createFullLogEvents")
+    void test_full_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_full_log_events()
+    private static Stream<Arguments> createFullLogEvents() {
+        return LogEventFixture
+                .createFullLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    void verifySerialization(final LogEvent logEvent) {
+        usingSerializedLogEventAccessor(LAYOUT, logEvent, accessor -> {
+
+            // Verify timestamp.
+            final String expectedTimestamp = formatLogEventInstant(logEvent);
+            assertThat(accessor.getString("timestamp")).isEqualTo(expectedTimestamp);
+
+            // Verify severity.
+            final Level level = logEvent.getLevel();
+            final String expectedSeverity;
+            if (Level.WARN.equals(level)) {
+                expectedSeverity = "WARNING";
+            } else if (Level.TRACE.equals(level)) {
+                expectedSeverity = "TRACE";
+            } else if (Level.FATAL.equals(level)) {
+                expectedSeverity = "EMERGENCY";
+            } else {
+                expectedSeverity = level.name();
+            }
+            assertThat(accessor.getString("severity")).isEqualTo(expectedSeverity);
+
+            // Verify message.
+            final String expectedMessage = logEvent.getMessage().getFormattedMessage();
+            assertThat(accessor.getString("message")).contains(expectedMessage);
+            final Throwable exception = logEvent.getThrown();
+            if (exception != null) {
+                final String expectedExceptionMessage = exception.getLocalizedMessage();
+                assertThat(accessor.getString("message")).contains(expectedExceptionMessage);

Review comment:
       Settled down to a very ugly solution:
   ```java
   final String actualMessage = accessor.getString("message");
   assertThat(actualMessage)
           .contains(logEvent.getMessage().getFormattedMessage())
           .contains(exception.getLocalizedMessage())
           .contains("at org.apache.logging.log4j.layout.template.json")
           .contains("at java.util.stream.ForEachOps")
           .contains("at org.junit.platform.engine");
   ```
   `ThrowablePatternConverterTest` doesn't do a terrific job either. Hence, should be okay.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@logging.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [logging-log4j2] vy commented on pull request #551: LOG4J2-3116 Add GCP logging layout

Posted by GitBox <gi...@apache.org>.
vy commented on pull request #551:
URL: https://github.com/apache/logging-log4j2/pull/551#issuecomment-882917321


   @rocketraman, thanks so much again. I will do necessary git magic tomorrow to make your commits in #543 visible.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@logging.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [logging-log4j2] vy commented on a change in pull request #551: LOG4J2-3116 Add GCP logging layout

Posted by GitBox <gi...@apache.org>.
vy commented on a change in pull request #551:
URL: https://github.com/apache/logging-log4j2/pull/551#discussion_r672688480



##########
File path: log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/GcpLayoutTest.java
##########
@@ -0,0 +1,221 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.logging.log4j.layout.template.json;
+
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.core.LogEvent;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintWriter;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.Locale;
+import java.util.stream.Stream;
+
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.CONFIGURATION;
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.usingSerializedLogEventAccessor;
+import static org.assertj.core.api.Assertions.assertThat;
+
+class GcpLayoutTest {
+
+    private static final JsonTemplateLayout LAYOUT = JsonTemplateLayout
+            .newBuilder()
+            .setConfiguration(CONFIGURATION)
+            .setStackTraceEnabled(true)
+            .setLocationInfoEnabled(true)
+            .setEventTemplateUri("classpath:GcpLayout.json")
+            .build();
+
+    private static final int LOG_EVENT_COUNT = 1_000;
+
+    private static final DateTimeFormatter DATE_TIME_FORMATTER =
+            DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
+
+    @ParameterizedTest
+    @MethodSource("createLiteLogEvents")
+    void test_lite_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_lite_log_events()
+    private static Stream<Arguments> createLiteLogEvents() {
+        return LogEventFixture
+                .createLiteLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    @ParameterizedTest
+    @MethodSource("createFullLogEvents")
+    void test_full_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_full_log_events()
+    private static Stream<Arguments> createFullLogEvents() {
+        return LogEventFixture
+                .createFullLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    void verifySerialization(final LogEvent logEvent) {
+        usingSerializedLogEventAccessor(LAYOUT, logEvent, accessor -> {
+
+            // Verify timestamp.
+            final String expectedTimestamp = formatLogEventInstant(logEvent);
+            assertThat(accessor.getString("timestamp")).isEqualTo(expectedTimestamp);
+
+            // Verify severity.
+            final Level level = logEvent.getLevel();
+            final String expectedSeverity;
+            if (Level.WARN.equals(level)) {
+                expectedSeverity = "WARNING";
+            } else if (Level.TRACE.equals(level)) {
+                expectedSeverity = "TRACE";
+            } else if (Level.FATAL.equals(level)) {
+                expectedSeverity = "EMERGENCY";
+            } else {
+                expectedSeverity = level.name();
+            }
+            assertThat(accessor.getString("severity")).isEqualTo(expectedSeverity);
+
+            // Verify message.
+            final String expectedMessage = logEvent.getMessage().getFormattedMessage();
+            assertThat(accessor.getString("message")).contains(expectedMessage);
+            final Throwable exception = logEvent.getThrown();
+            if (exception != null) {
+                final String expectedExceptionMessage = exception.getLocalizedMessage();
+                assertThat(accessor.getString("message")).contains(expectedExceptionMessage);

Review comment:
       Settled down to a very ugly solution:
   ```java
   final String actualMessage = accessor.getString("message");
   assertThat(actualMessage)
           .contains(logEvent.getMessage().getFormattedMessage())
           .contains(exception.getLocalizedMessage())
           .contains("at org.apache.logging.log4j.layout.template.json")
           .contains("at java.util.stream.ForEachOps")
           .contains("at org.junit.platform.engine");
   ```
   `ThrowablePatternConverterTest` doesn't do a terrific job either. Hence, should be okay.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@logging.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [logging-log4j2] vy commented on a change in pull request #551: LOG4J2-3116 Add GCP logging layout

Posted by GitBox <gi...@apache.org>.
vy commented on a change in pull request #551:
URL: https://github.com/apache/logging-log4j2/pull/551#discussion_r672678885



##########
File path: log4j-layout-template-json/src/main/resources/GcpLayout.json
##########
@@ -0,0 +1,67 @@
+{
+  "timestamp": {
+    "$resolver": "timestamp",
+    "pattern": {
+      "format": "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
+      "timeZone": "UTC",
+      "locale": "en_US"
+    }
+  },
+  "severity": {
+    "$resolver": "pattern",
+    "pattern": "%level{WARN=WARNING, TRACE=DEBUG, FATAL=EMERGENCY}",
+    "stackTraceEnabled": false
+  },
+  "message": {
+    "$resolver": "pattern",
+    "pattern": "%m"

Review comment:
       Good catch! Will do.

##########
File path: log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/GcpLayoutTest.java
##########
@@ -0,0 +1,221 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.logging.log4j.layout.template.json;
+
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.core.LogEvent;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintWriter;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.Locale;
+import java.util.stream.Stream;
+
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.CONFIGURATION;
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.usingSerializedLogEventAccessor;
+import static org.assertj.core.api.Assertions.assertThat;
+
+class GcpLayoutTest {
+
+    private static final JsonTemplateLayout LAYOUT = JsonTemplateLayout
+            .newBuilder()
+            .setConfiguration(CONFIGURATION)
+            .setStackTraceEnabled(true)
+            .setLocationInfoEnabled(true)
+            .setEventTemplateUri("classpath:GcpLayout.json")
+            .build();
+
+    private static final int LOG_EVENT_COUNT = 1_000;
+
+    private static final DateTimeFormatter DATE_TIME_FORMATTER =
+            DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
+
+    @ParameterizedTest
+    @MethodSource("createLiteLogEvents")
+    void test_lite_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_lite_log_events()
+    private static Stream<Arguments> createLiteLogEvents() {
+        return LogEventFixture
+                .createLiteLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    @ParameterizedTest
+    @MethodSource("createFullLogEvents")
+    void test_full_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_full_log_events()
+    private static Stream<Arguments> createFullLogEvents() {
+        return LogEventFixture
+                .createFullLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    void verifySerialization(final LogEvent logEvent) {
+        usingSerializedLogEventAccessor(LAYOUT, logEvent, accessor -> {
+
+            // Verify timestamp.
+            final String expectedTimestamp = formatLogEventInstant(logEvent);
+            assertThat(accessor.getString("timestamp")).isEqualTo(expectedTimestamp);
+
+            // Verify severity.
+            final Level level = logEvent.getLevel();
+            final String expectedSeverity;
+            if (Level.WARN.equals(level)) {
+                expectedSeverity = "WARNING";
+            } else if (Level.TRACE.equals(level)) {
+                expectedSeverity = "TRACE";
+            } else if (Level.FATAL.equals(level)) {
+                expectedSeverity = "EMERGENCY";
+            } else {
+                expectedSeverity = level.name();
+            }
+            assertThat(accessor.getString("severity")).isEqualTo(expectedSeverity);
+
+            // Verify message.
+            final String expectedMessage = logEvent.getMessage().getFormattedMessage();
+            assertThat(accessor.getString("message")).contains(expectedMessage);
+            final Throwable exception = logEvent.getThrown();
+            if (exception != null) {
+                final String expectedExceptionMessage = exception.getLocalizedMessage();
+                assertThat(accessor.getString("message")).contains(expectedExceptionMessage);

Review comment:
       Was working on this and... It has turned out to be pretty difficult. `PatternLayout`s `ExtendedThrowablePatternConverter` uses `ThrowableProxy`, which has a pretty different way of working than `JsonTemplateLayout`s `StackTraceStringResolver`. In order to make `message` and `_exception.stackTrace` match, I needed to make the latter use `%xEx` pattern too. Yet, I still could not succeed in reproducing the `PatternLayout`-serialized stack trace in tests. I will continue working on this tomorrow.

##########
File path: log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/GcpLayoutTest.java
##########
@@ -0,0 +1,221 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.logging.log4j.layout.template.json;
+
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.core.LogEvent;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintWriter;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.Locale;
+import java.util.stream.Stream;
+
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.CONFIGURATION;
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.usingSerializedLogEventAccessor;
+import static org.assertj.core.api.Assertions.assertThat;
+
+class GcpLayoutTest {
+
+    private static final JsonTemplateLayout LAYOUT = JsonTemplateLayout
+            .newBuilder()
+            .setConfiguration(CONFIGURATION)
+            .setStackTraceEnabled(true)
+            .setLocationInfoEnabled(true)
+            .setEventTemplateUri("classpath:GcpLayout.json")
+            .build();
+
+    private static final int LOG_EVENT_COUNT = 1_000;
+
+    private static final DateTimeFormatter DATE_TIME_FORMATTER =
+            DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
+
+    @ParameterizedTest
+    @MethodSource("createLiteLogEvents")
+    void test_lite_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_lite_log_events()
+    private static Stream<Arguments> createLiteLogEvents() {
+        return LogEventFixture
+                .createLiteLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    @ParameterizedTest
+    @MethodSource("createFullLogEvents")
+    void test_full_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_full_log_events()
+    private static Stream<Arguments> createFullLogEvents() {
+        return LogEventFixture
+                .createFullLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    void verifySerialization(final LogEvent logEvent) {
+        usingSerializedLogEventAccessor(LAYOUT, logEvent, accessor -> {
+
+            // Verify timestamp.
+            final String expectedTimestamp = formatLogEventInstant(logEvent);
+            assertThat(accessor.getString("timestamp")).isEqualTo(expectedTimestamp);
+
+            // Verify severity.
+            final Level level = logEvent.getLevel();
+            final String expectedSeverity;
+            if (Level.WARN.equals(level)) {
+                expectedSeverity = "WARNING";
+            } else if (Level.TRACE.equals(level)) {
+                expectedSeverity = "TRACE";
+            } else if (Level.FATAL.equals(level)) {
+                expectedSeverity = "EMERGENCY";
+            } else {
+                expectedSeverity = level.name();
+            }
+            assertThat(accessor.getString("severity")).isEqualTo(expectedSeverity);
+
+            // Verify message.
+            final String expectedMessage = logEvent.getMessage().getFormattedMessage();
+            assertThat(accessor.getString("message")).contains(expectedMessage);
+            final Throwable exception = logEvent.getThrown();
+            if (exception != null) {
+                final String expectedExceptionMessage = exception.getLocalizedMessage();
+                assertThat(accessor.getString("message")).contains(expectedExceptionMessage);

Review comment:
       Settled down to a very ugly solution:
   ```java
   final String actualMessage = accessor.getString("message");
   assertThat(actualMessage)
           .contains(logEvent.getMessage().getFormattedMessage())
           .contains(exception.getLocalizedMessage())
           .contains("at org.apache.logging.log4j.layout.template.json")
           .contains("at java.util.stream.ForEachOps")
           .contains("at org.junit.platform.engine");
   ```
   `ThrowablePatternConverterTest` doesn't do a terrific job either. Hence, should be okay.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@logging.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [logging-log4j2] vy closed pull request #551: LOG4J2-3116 Add GCP logging layout

Posted by GitBox <gi...@apache.org>.
vy closed pull request #551:
URL: https://github.com/apache/logging-log4j2/pull/551


   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@logging.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [logging-log4j2] vy commented on pull request #551: LOG4J2-3116 Add GCP logging layout

Posted by GitBox <gi...@apache.org>.
vy commented on pull request #551:
URL: https://github.com/apache/logging-log4j2/pull/551#issuecomment-882917321


   @rocketraman, thanks so much again. I will do necessary git magic tomorrow to make your commits in #543 visible.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@logging.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [logging-log4j2] rocketraman commented on a change in pull request #551: LOG4J2-3116 Add GCP logging layout

Posted by GitBox <gi...@apache.org>.
rocketraman commented on a change in pull request #551:
URL: https://github.com/apache/logging-log4j2/pull/551#discussion_r672657984



##########
File path: log4j-layout-template-json/src/main/resources/GcpLayout.json
##########
@@ -0,0 +1,67 @@
+{
+  "timestamp": {
+    "$resolver": "timestamp",
+    "pattern": {
+      "format": "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
+      "timeZone": "UTC",
+      "locale": "en_US"
+    }
+  },
+  "severity": {
+    "$resolver": "pattern",
+    "pattern": "%level{WARN=WARNING, TRACE=DEBUG, FATAL=EMERGENCY}",
+    "stackTraceEnabled": false
+  },
+  "message": {
+    "$resolver": "pattern",
+    "pattern": "%m"

Review comment:
       I see you removed `stackTraceEnabled` setting here. I believe stackTraceEnabled defaults to `true` so that has no practical impact, but because Google's documentation is clear that the stack trace should be added to the `message` field, I felt that explicitly adding that attribute here was a useful hint / recognition of the explicit design of this layout.

##########
File path: log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/GcpLayoutTest.java
##########
@@ -0,0 +1,221 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.logging.log4j.layout.template.json;
+
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.core.LogEvent;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintWriter;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.Locale;
+import java.util.stream.Stream;
+
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.CONFIGURATION;
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.usingSerializedLogEventAccessor;
+import static org.assertj.core.api.Assertions.assertThat;
+
+class GcpLayoutTest {
+
+    private static final JsonTemplateLayout LAYOUT = JsonTemplateLayout
+            .newBuilder()
+            .setConfiguration(CONFIGURATION)
+            .setStackTraceEnabled(true)
+            .setLocationInfoEnabled(true)
+            .setEventTemplateUri("classpath:GcpLayout.json")
+            .build();
+
+    private static final int LOG_EVENT_COUNT = 1_000;
+
+    private static final DateTimeFormatter DATE_TIME_FORMATTER =
+            DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
+
+    @ParameterizedTest
+    @MethodSource("createLiteLogEvents")
+    void test_lite_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_lite_log_events()
+    private static Stream<Arguments> createLiteLogEvents() {
+        return LogEventFixture
+                .createLiteLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    @ParameterizedTest
+    @MethodSource("createFullLogEvents")
+    void test_full_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_full_log_events()
+    private static Stream<Arguments> createFullLogEvents() {
+        return LogEventFixture
+                .createFullLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    void verifySerialization(final LogEvent logEvent) {
+        usingSerializedLogEventAccessor(LAYOUT, logEvent, accessor -> {
+
+            // Verify timestamp.
+            final String expectedTimestamp = formatLogEventInstant(logEvent);
+            assertThat(accessor.getString("timestamp")).isEqualTo(expectedTimestamp);
+
+            // Verify severity.
+            final Level level = logEvent.getLevel();
+            final String expectedSeverity;
+            if (Level.WARN.equals(level)) {
+                expectedSeverity = "WARNING";
+            } else if (Level.TRACE.equals(level)) {
+                expectedSeverity = "TRACE";
+            } else if (Level.FATAL.equals(level)) {
+                expectedSeverity = "EMERGENCY";
+            } else {
+                expectedSeverity = level.name();
+            }
+            assertThat(accessor.getString("severity")).isEqualTo(expectedSeverity);
+
+            // Verify message.
+            final String expectedMessage = logEvent.getMessage().getFormattedMessage();
+            assertThat(accessor.getString("message")).contains(expectedMessage);
+            final Throwable exception = logEvent.getThrown();
+            if (exception != null) {
+                final String expectedExceptionMessage = exception.getLocalizedMessage();
+                assertThat(accessor.getString("message")).contains(expectedExceptionMessage);
+            }
+
+            // Verify labels.
+            logEvent.getContextData().forEach((key, value) -> {
+                final String expectedValue = String.valueOf(value);
+                final String actualValue =
+                        accessor.getString(new String[]{
+                                "logging.googleapis.com/labels", key});
+                assertThat(actualValue).isEqualTo(expectedValue);
+            });
+
+            final StackTraceElement source = logEvent.getSource();
+            if (source != null) {
+
+                // Verify file name.
+                final String actualFileName =
+                        accessor.getString(new String[]{
+                        "logging.googleapis.com/sourceLocation", "file"});
+                assertThat(actualFileName).isEqualTo(source.getFileName());
+
+                // Verify line number.
+                final int actualLineNumber =
+                        accessor.getInteger(new String[]{
+                                "logging.googleapis.com/sourceLocation", "line"});
+                assertThat(actualLineNumber).isEqualTo(source.getLineNumber());
+
+                // Verify function.
+                final String expectedFunction =
+                        source.getClassName() + "." + source.getMethodName();
+                final String actualFunction =
+                        accessor.getString(new String[]{
+                                "logging.googleapis.com/sourceLocation", "function"});
+                assertThat(actualFunction).isEqualTo(expectedFunction);
+
+            } else {
+                assertThat(accessor.exists(
+                        new String[]{"logging.googleapis.com/sourceLocation", "file"}))
+                        .isFalse();
+                assertThat(accessor.exists(
+                        new String[]{"logging.googleapis.com/sourceLocation", "line"}))
+                        .isFalse();
+                assertThat(accessor.getString(
+                        new String[]{"logging.googleapis.com/sourceLocation", "function"}))
+                        .isEmpty();
+            }
+
+            // Verify insert id.
+            assertThat(accessor.getString("logging.googleapis.com/insertId"))
+                    .matches("[-]?[0-9]+");
+
+            // Verify exception.
+            if (exception != null) {
+
+                // Verify exception class.
+                assertThat(accessor.getString(
+                        new String[]{"_exception", "class"}))
+                        .isEqualTo(exception.getClass().getCanonicalName());
+
+                // Verify exception message.
+                assertThat(accessor.getString(
+                        new String[]{"_exception", "message"}))
+                        .isEqualTo(exception.getMessage());
+
+                // Verify exception stack trace.
+                final String expectedExceptionStackTrace =
+                        serializeThrowableStackTrace(exception);
+                assertThat(accessor.getString(
+                        new String[]{"_exception", "stackTrace"}))
+                        .isEqualTo(expectedExceptionStackTrace);
+
+            } else {
+                assertThat(accessor.getObject(
+                        new String[]{"_exception", "class"}))
+                        .isNull();
+                assertThat(accessor.getObject(
+                        new String[]{"_exception", "message"}))
+                        .isNull();
+                assertThat(accessor.getObject(
+                        new String[]{"_exception", "stackTrace"}))
+                        .isNull();
+            }
+
+            // Verify thread name.
+            assertThat(accessor.getString("_thread"))
+                    .isEqualTo(logEvent.getThreadName());
+
+            // Verify logger name.
+            assertThat(accessor.getString("_logger"))
+                    .isEqualTo(logEvent.getLoggerName());
+
+        });

Review comment:
       Much better than my version of the test, thanks. I think I got off on the wrong foot by using Ecs and Gelf layout tests as a starting point.

##########
File path: log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/GcpLayoutTest.java
##########
@@ -0,0 +1,221 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.logging.log4j.layout.template.json;
+
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.core.LogEvent;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintWriter;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.Locale;
+import java.util.stream.Stream;
+
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.CONFIGURATION;
+import static org.apache.logging.log4j.layout.template.json.TestHelpers.usingSerializedLogEventAccessor;
+import static org.assertj.core.api.Assertions.assertThat;
+
+class GcpLayoutTest {
+
+    private static final JsonTemplateLayout LAYOUT = JsonTemplateLayout
+            .newBuilder()
+            .setConfiguration(CONFIGURATION)
+            .setStackTraceEnabled(true)
+            .setLocationInfoEnabled(true)
+            .setEventTemplateUri("classpath:GcpLayout.json")
+            .build();
+
+    private static final int LOG_EVENT_COUNT = 1_000;
+
+    private static final DateTimeFormatter DATE_TIME_FORMATTER =
+            DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
+
+    @ParameterizedTest
+    @MethodSource("createLiteLogEvents")
+    void test_lite_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_lite_log_events()
+    private static Stream<Arguments> createLiteLogEvents() {
+        return LogEventFixture
+                .createLiteLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    @ParameterizedTest
+    @MethodSource("createFullLogEvents")
+    void test_full_log_events(final LogEvent logEvent) {
+        verifySerialization(logEvent);
+    }
+
+    @SuppressWarnings("unused")     // supplies arguments to test_full_log_events()
+    private static Stream<Arguments> createFullLogEvents() {
+        return LogEventFixture
+                .createFullLogEvents(LOG_EVENT_COUNT)
+                .stream()
+                .map(Arguments::arguments);
+    }
+
+    void verifySerialization(final LogEvent logEvent) {
+        usingSerializedLogEventAccessor(LAYOUT, logEvent, accessor -> {
+
+            // Verify timestamp.
+            final String expectedTimestamp = formatLogEventInstant(logEvent);
+            assertThat(accessor.getString("timestamp")).isEqualTo(expectedTimestamp);
+
+            // Verify severity.
+            final Level level = logEvent.getLevel();
+            final String expectedSeverity;
+            if (Level.WARN.equals(level)) {
+                expectedSeverity = "WARNING";
+            } else if (Level.TRACE.equals(level)) {
+                expectedSeverity = "TRACE";
+            } else if (Level.FATAL.equals(level)) {
+                expectedSeverity = "EMERGENCY";
+            } else {
+                expectedSeverity = level.name();
+            }
+            assertThat(accessor.getString("severity")).isEqualTo(expectedSeverity);
+
+            // Verify message.
+            final String expectedMessage = logEvent.getMessage().getFormattedMessage();
+            assertThat(accessor.getString("message")).contains(expectedMessage);
+            final Throwable exception = logEvent.getThrown();
+            if (exception != null) {
+                final String expectedExceptionMessage = exception.getLocalizedMessage();
+                assertThat(accessor.getString("message")).contains(expectedExceptionMessage);

Review comment:
       Can we add a test for the stack trace being in the message? This just tests the exception message.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@logging.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [logging-log4j2] vy commented on pull request #551: LOG4J2-3116 Add GCP logging layout

Posted by GitBox <gi...@apache.org>.
vy commented on pull request #551:
URL: https://github.com/apache/logging-log4j2/pull/551#issuecomment-882917321


   @rocketraman, thanks so much again. I will do necessary git magic tomorrow to make your commits in #543 visible.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@logging.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org