From ced0a5799430c1baf83eb83e9694c8cbad05a815 Mon Sep 17 00:00:00 2001 From: Johan Chavaillaz Date: Sat, 20 Jan 2024 03:58:13 +0100 Subject: [PATCH] Add first version of the project. --- .github/workflows/maven-publish.yml | 31 ++ .github/workflows/system-tests.yml | 30 ++ .gitignore | 43 +++ .idea/encodings.xml | 7 + .idea/misc.xml | 33 ++ .../Maven_Check_Dependencies.xml | 32 ++ .../runConfigurations/Maven_Check_Plugins.xml | 32 ++ .idea/vcs.xml | 6 + LICENSE | 201 +++++++++++++ pom.xml | 282 ++++++++++++++++++ release.sh | 12 + .../com/chavaillaz/jakarta/rs/Logged.java | 37 +++ .../chavaillaz/jakarta/rs/LoggedFilter.java | 251 ++++++++++++++++ .../jakarta/rs/InMemoryAppender.java | 61 ++++ .../jakarta/rs/LoggedFilterTest.java | 153 ++++++++++ src/test/resources/log4j2.xml | 13 + 16 files changed, 1224 insertions(+) create mode 100644 .github/workflows/maven-publish.yml create mode 100644 .github/workflows/system-tests.yml create mode 100644 .gitignore create mode 100644 .idea/encodings.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/runConfigurations/Maven_Check_Dependencies.xml create mode 100644 .idea/runConfigurations/Maven_Check_Plugins.xml create mode 100644 .idea/vcs.xml create mode 100644 LICENSE create mode 100644 pom.xml create mode 100644 release.sh create mode 100644 src/main/java/com/chavaillaz/jakarta/rs/Logged.java create mode 100644 src/main/java/com/chavaillaz/jakarta/rs/LoggedFilter.java create mode 100644 src/test/java/com/chavaillaz/jakarta/rs/InMemoryAppender.java create mode 100644 src/test/java/com/chavaillaz/jakarta/rs/LoggedFilterTest.java create mode 100644 src/test/resources/log4j2.xml diff --git a/.github/workflows/maven-publish.yml b/.github/workflows/maven-publish.yml new file mode 100644 index 0000000..7ed7925 --- /dev/null +++ b/.github/workflows/maven-publish.yml @@ -0,0 +1,31 @@ +name: Publish to Maven Central +on: + release: + types: [ created ] +jobs: + build: + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Set up for publishing to Maven Central Repository + uses: actions/setup-java@v3 + with: + java-version: '21' + distribution: 'temurin' + server-id: ossrh + server-username: MAVEN_USERNAME + server-password: MAVEN_PASSWORD + gpg-private-key: ${{ secrets.GPG_SIGNING_KEY }} + gpg-passphrase: MAVEN_GPG_PASSPHRASE + + - name: Publish to Maven Central Repository + run: mvn --batch-mode deploy -Prelease -DskipTests + env: + MAVEN_USERNAME: ${{ secrets.OSSRH_USERNAME }} + MAVEN_PASSWORD: ${{ secrets.OSSRH_TOKEN }} + MAVEN_GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} \ No newline at end of file diff --git a/.github/workflows/system-tests.yml b/.github/workflows/system-tests.yml new file mode 100644 index 0000000..6cd8870 --- /dev/null +++ b/.github/workflows/system-tests.yml @@ -0,0 +1,30 @@ +name: System tests +on: [ push, pull_request_target ] +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Check out + uses: actions/checkout@master + + - name: Set up + uses: actions/setup-java@master + with: + java-version: '21' + distribution: 'temurin' + + - name: Build project + run: mvn -B -Pcoverage verify + + - name: Run Snyk to check for vulnerabilities + uses: snyk/actions/maven@master + continue-on-error: true + env: + SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }} + with: + args: --sarif-file-output=snyk.sarif --include-provided-dependencies=false + + - name: Upload result to GitHub Code Scanning + uses: github/codeql-action/upload-sarif@v2 + with: + sarif_file: snyk.sarif \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..491348f --- /dev/null +++ b/.gitignore @@ -0,0 +1,43 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### IntelliJ IDEA ### +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Maven with auto-import +.idea/artifacts +.idea/compiler.xml +.idea/jarRepositories.xml +.idea/modules.xml +.idea/*.iml +.idea/modules +*.iml +*.ipr + +### OS generated files +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +ehthumbs.db +Thumbs.db \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..aa00ffa --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..67acf40 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations/Maven_Check_Dependencies.xml b/.idea/runConfigurations/Maven_Check_Dependencies.xml new file mode 100644 index 0000000..86128c2 --- /dev/null +++ b/.idea/runConfigurations/Maven_Check_Dependencies.xml @@ -0,0 +1,32 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations/Maven_Check_Plugins.xml b/.idea/runConfigurations/Maven_Check_Plugins.xml new file mode 100644 index 0000000..f4a7832 --- /dev/null +++ b/.idea/runConfigurations/Maven_Check_Plugins.xml @@ -0,0 +1,32 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..6f7bf9d --- /dev/null +++ b/pom.xml @@ -0,0 +1,282 @@ + + + 4.0.0 + + com.chavaillaz + jaxrs-logging + 1.0-SNAPSHOT + jar + + ${project.groupId}.${project.artifactId} + Library to log requests and responses of JAX-RS resources with MDC + https://github.com/chavaillaz/jaxrs-logging + + + scm:git:https://github.com/chavaillaz/jaxrs-logging.git + scm:git:ssh://github.com/chavaillaz/jaxrs-logging.git + https://github.com/chavaillaz/jaxrs-logging + HEAD + + + + + Chavjoh + Johan Chavaillaz + + + + + + Apache License 2.0 + https://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + UTF-8 + UTF-8 + + + + + + org.apache.logging.log4j + log4j-bom + 2.22.1 + pom + import + + + + + + + jakarta.platform + jakarta.jakartaee-web-api + 10.0.0 + provided + + + + commons-io + commons-io + 2.15.1 + + + + org.slf4j + slf4j-api + 2.0.11 + + + + + + org.jboss.resteasy + resteasy-core + 6.2.7.Final + test + + + + org.junit.jupiter + junit-jupiter-engine + 5.10.1 + test + + + + org.mockito + mockito-junit-jupiter + 5.9.0 + test + + + + org.apache.logging.log4j + log4j-core + test + + + + org.apache.logging.log4j + log4j-slf4j2-impl + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.12.1 + + 11 + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.2.5 + + + + org.apache.maven.plugins + maven-dependency-plugin + 3.6.1 + + + + org.apache.maven.plugins + maven-assembly-plugin + 3.6.0 + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.4.1 + + + enforce-maven + + enforce + + + + + 3.8 + + + + + + + + + io.smallrye + jandex-maven-plugin + 3.1.6 + + + make-index + + jandex + + + + + + + + + + release + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.6.3 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 3.3.0 + + + attach-sources + + jar + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 3.1.0 + + + + --pinentry-mode + loopback + + + + + sign-artifacts + verify + + sign + + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.13 + true + + ossrh + https://oss.sonatype.org/ + true + + + + + + + coverage + + + + org.jacoco + jacoco-maven-plugin + 0.8.11 + + + prepare-agent + + prepare-agent + + + + report + + report + + + + + + + + + + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + + + ossrh + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + + \ No newline at end of file diff --git a/release.sh b/release.sh new file mode 100644 index 0000000..69ea2ba --- /dev/null +++ b/release.sh @@ -0,0 +1,12 @@ +# Same as -> export newVersion=x.x.x +echo "Enter version number (x.x.x): " +read newVersion +export GPG_TTY=$(tty) +mvn versions:set -DnewVersion=${newVersion} -DgenerateBackupPoms=false +# mvn clean deploy -Prelease -> Done by Github actions +git add . +git commit -m "Release ${newVersion}" +git tag ${newVersion} +git push --tags +git reset HEAD~1 +git checkout . \ No newline at end of file diff --git a/src/main/java/com/chavaillaz/jakarta/rs/Logged.java b/src/main/java/com/chavaillaz/jakarta/rs/Logged.java new file mode 100644 index 0000000..6fcb90f --- /dev/null +++ b/src/main/java/com/chavaillaz/jakarta/rs/Logged.java @@ -0,0 +1,37 @@ +package com.chavaillaz.jakarta.rs; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import jakarta.ws.rs.NameBinding; + +/** + * Annotation activating the filter {@link LoggedFilter} + * in order to log incoming requests received by a JAX-RS resource. + */ +@Documented +@NameBinding +@Retention(RUNTIME) +@Target({TYPE, METHOD}) +public @interface Logged { + + /** + * Indicates if the request body must be as MDC field when logging the request. + * + * @return {@code true} to log the request body, {@code false} otherwise + */ + boolean requestBody() default false; + + /** + * Indicates if the response body must be as MDC field when logging the request. + * + * @return {@code true} to log the response body, {@code false} otherwise + */ + boolean responseBody() default false; + +} diff --git a/src/main/java/com/chavaillaz/jakarta/rs/LoggedFilter.java b/src/main/java/com/chavaillaz/jakarta/rs/LoggedFilter.java new file mode 100644 index 0000000..c708d94 --- /dev/null +++ b/src/main/java/com/chavaillaz/jakarta/rs/LoggedFilter.java @@ -0,0 +1,251 @@ +package com.chavaillaz.jakarta.rs; + +import static java.lang.String.valueOf; +import static java.lang.System.nanoTime; +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Optional.empty; +import static java.util.Optional.of; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.util.Optional; +import java.util.UUID; + +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.container.ContainerRequestFilter; +import jakarta.ws.rs.container.ContainerResponseContext; +import jakarta.ws.rs.container.ContainerResponseFilter; +import jakarta.ws.rs.container.ResourceInfo; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.UriInfo; +import jakarta.ws.rs.ext.MessageBodyWriter; +import jakarta.ws.rs.ext.Provider; +import jakarta.ws.rs.ext.Providers; +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; + +/** + * Provider adding the following request information to {@link MDC}: + * + * Once the response computed, the request will be logged using the format + * Processed [method] [URI] with status [status] in [duration]ms + * with the following {@link MDC}: + * + * This filter can be activated using the annotation {@link Logged} on resources. + */ +@Logged +@Provider +public class LoggedFilter implements ContainerRequestFilter, ContainerResponseFilter { + + protected static final Logger log = LoggerFactory.getLogger(LoggedFilter.class); + + protected static final String DURATION = "duration"; + protected static final String REQUEST_ID = "request-id"; + protected static final String REQUEST_TIME = "request-time"; + protected static final String REQUEST_METHOD = "request-method"; + protected static final String REQUEST_URI = "request-uri"; + protected static final String REQUEST_BODY = "request-body"; + protected static final String RESPONSE_BODY = "response-body"; + protected static final String RESPONSE_STATUS = "response-status"; + protected static final String RESOURCE_CLASS = "resource-class"; + protected static final String RESOURCE_METHOD = "resource-method"; + + @Context + ResourceInfo resourceInfo; + + @Context + Providers providers; + + /** + * Gets the given annotation from the resource method or class matched by the current request. + * + * @param resourceInfo The instance to access resource class and method + * @param annotation The annotation type to get + * @param The annotation type + * @return The annotation found or {@link Optional#empty} otherwise + */ + protected static Optional getAnnotation(ResourceInfo resourceInfo, Class annotation) { + if (resourceInfo.getResourceMethod().isAnnotationPresent(annotation)) { + return of(resourceInfo.getResourceMethod().getAnnotation(annotation)); + } else if (resourceInfo.getResourceClass().isAnnotationPresent(annotation)) { + return of(resourceInfo.getResourceClass().getAnnotation(annotation)); + } else { + return empty(); + } + } + + /** + * Gets the annotation type used to activate this filter. + * Can be overridden for more specific annotation to be used when extending this filter. + * + * @return The annotation type + */ + protected Class getAnnotation() { + return Logged.class; + } + + /** + * Gets the request identifier that will be stored in MDC for the complete request processing. + * Returns a random UUID but can be overridden to return a business identifier based on the request. + * + * @param requestContext The context of the request received + * @return The request identifier + */ + protected String getRequestId(ContainerRequestContext requestContext) { + return UUID.randomUUID().toString(); + } + + @Override + public void filter(ContainerRequestContext requestContext) { + String requestId = getRequestId(requestContext); + requestContext.setProperty(REQUEST_ID, requestId); + MDC.put(REQUEST_ID, requestId); + + requestContext.setProperty(REQUEST_TIME, nanoTime()); + + Optional.of(requestContext.getUriInfo()) + .map(UriInfo::getPath) + .ifPresent(path -> MDC.put(REQUEST_URI, path)); + + MDC.put(REQUEST_METHOD, requestContext.getMethod()); + + Optional.ofNullable(resourceInfo.getResourceClass()) + .map(Class::getSimpleName) + .ifPresent(value -> MDC.put(RESOURCE_CLASS, value)); + + Optional.ofNullable(resourceInfo.getResourceMethod()) + .map(Method::getName) + .ifPresent(value -> MDC.put(RESOURCE_METHOD, value)); + } + + @Override + public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) { + long requestStartTime = Optional.ofNullable(requestContext.getProperty(REQUEST_TIME)) + .map(Object::toString) + .map(Long::parseLong) + .orElse(nanoTime()); + long duration = (nanoTime() - requestStartTime) / 1_000_000; + MDC.put(DURATION, valueOf(duration)); + + MDC.put(RESPONSE_STATUS, valueOf(responseContext.getStatus())); + + logRequestBody(requestContext); + logResponseBody(responseContext); + + log.info("Processed {} {} with status {} in {}ms", + requestContext.getMethod(), + requestContext.getUriInfo().getPath(), + responseContext.getStatus(), + duration); + + cleanupMdc(); + } + + /** + * Logs the request body in the corresponding MDC field if activated in the annotation. + * + * @param requestContext The context of the request + */ + protected void logRequestBody(ContainerRequestContext requestContext) { + getAnnotation(resourceInfo, getAnnotation()) + .map(Logged::requestBody) + .filter(loggingActivated -> loggingActivated && requestContext.hasEntity()) + .ifPresent(logging -> MDC.put(REQUEST_BODY, getRequestBody(requestContext))); + } + + /** + * Logs the response body in the corresponding MDC field if activated in the annotation. + * + * @param responseContext THe context of the response + */ + protected void logResponseBody(ContainerResponseContext responseContext) { + getAnnotation(resourceInfo, getAnnotation()) + .map(Logged::responseBody) + .filter(loggingActivated -> loggingActivated && responseContext.hasEntity()) + .ifPresent(logging -> MDC.put(RESPONSE_BODY, getResponseBody(responseContext))); + } + + /** + * Extracts the request body as {@link String}. + * + * @param requestContext The context of the request + * @return The request body or the message of the exception thrown + */ + protected String getRequestBody(ContainerRequestContext requestContext) { + try (BufferedInputStream stream = new BufferedInputStream(requestContext.getEntityStream())) { + String payload = IOUtils.toString(stream, UTF_8); + requestContext.setEntityStream(IOUtils.toInputStream(payload, UTF_8)); + return payload; + } catch (IOException e) { + return e.getMessage(); + } + } + + /** + * Extracts the response body and parses it to {@link String} using the right body writer. + * + * @param responseContext The context of the response + * @return The response body or the message of the exception thrown + */ + protected String getResponseBody(ContainerResponseContext responseContext) { + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + Class entityClass = responseContext.getEntityClass(); + Type entityType = responseContext.getEntityType(); + Annotation[] entityAnnotations = responseContext.getEntityAnnotations(); + MediaType mediaType = responseContext.getMediaType(); + // Get the right body writer to be used for the entity in response + var bodyWriter = (MessageBodyWriter) providers.getMessageBodyWriter( + entityClass, + entityType, + entityAnnotations, + mediaType + ); + bodyWriter.writeTo( + responseContext.getEntity(), + entityClass, + entityType, + entityAnnotations, + mediaType, + responseContext.getHeaders(), + outputStream + ); + return outputStream.toString(); + } catch (IOException e) { + return e.getMessage(); + } + } + + /** + * Removes all MDC fields defined in {@link #filter(ContainerRequestContext)} + * and {@link #filter(ContainerRequestContext, ContainerResponseContext)}. + */ + protected void cleanupMdc() { + MDC.remove(DURATION); + MDC.remove(REQUEST_ID); + MDC.remove(REQUEST_BODY); + MDC.remove(REQUEST_URI); + MDC.remove(REQUEST_METHOD); + MDC.remove(RESPONSE_BODY); + MDC.remove(RESPONSE_STATUS); + MDC.remove(RESOURCE_CLASS); + MDC.remove(RESOURCE_METHOD); + } + +} \ No newline at end of file diff --git a/src/test/java/com/chavaillaz/jakarta/rs/InMemoryAppender.java b/src/test/java/com/chavaillaz/jakarta/rs/InMemoryAppender.java new file mode 100644 index 0000000..7a41d96 --- /dev/null +++ b/src/test/java/com/chavaillaz/jakarta/rs/InMemoryAppender.java @@ -0,0 +1,61 @@ +package com.chavaillaz.jakarta.rs; + +import static org.apache.logging.log4j.core.layout.PatternLayout.createDefaultLayout; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import org.apache.logging.log4j.core.Appender; +import org.apache.logging.log4j.core.Core; +import org.apache.logging.log4j.core.Filter; +import org.apache.logging.log4j.core.Layout; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.appender.AbstractAppender; +import org.apache.logging.log4j.core.config.Property; +import org.apache.logging.log4j.core.config.plugins.Plugin; +import org.apache.logging.log4j.core.config.plugins.PluginAttribute; +import org.apache.logging.log4j.core.config.plugins.PluginElement; +import org.apache.logging.log4j.core.config.plugins.PluginFactory; + +@Plugin(name = InMemoryAppender.APPENDER_NAME, + category = Core.CATEGORY_NAME, + elementType = Appender.ELEMENT_TYPE) +public class InMemoryAppender extends AbstractAppender { + + public static final String APPENDER_NAME = "InMemoryAppender"; + + protected final List messages = new ArrayList<>(); + + protected InMemoryAppender(String name, Filter filter, Layout layout) { + super(name, filter, layout, false, Property.EMPTY_ARRAY); + } + + public static InMemoryAppender createDefaultAppender() { + return createAppender(null, null, null, null); + } + + @PluginFactory + public static InMemoryAppender createAppender( + @PluginAttribute("name") String name, + @PluginElement("Filter") Filter filter, + @PluginElement("Layout") Layout layout, + @PluginAttribute("otherAttribute") String otherAttribute) { + return new InMemoryAppender(name != null ? name : APPENDER_NAME, filter, layout != null ? layout : createDefaultLayout()); + } + + @Override + public void append(LogEvent event) { + getMessages().add(event); + } + + /** + * Gets the log messages received by the appender. + * + * @return The list of log messages + */ + public List getMessages() { + return this.messages; + } + +} \ No newline at end of file diff --git a/src/test/java/com/chavaillaz/jakarta/rs/LoggedFilterTest.java b/src/test/java/com/chavaillaz/jakarta/rs/LoggedFilterTest.java new file mode 100644 index 0000000..45ede41 --- /dev/null +++ b/src/test/java/com/chavaillaz/jakarta/rs/LoggedFilterTest.java @@ -0,0 +1,153 @@ +package com.chavaillaz.jakarta.rs; + +import static com.chavaillaz.jakarta.rs.LoggedFilter.DURATION; +import static com.chavaillaz.jakarta.rs.LoggedFilter.REQUEST_BODY; +import static com.chavaillaz.jakarta.rs.LoggedFilter.REQUEST_ID; +import static com.chavaillaz.jakarta.rs.LoggedFilter.REQUEST_METHOD; +import static com.chavaillaz.jakarta.rs.LoggedFilter.REQUEST_URI; +import static com.chavaillaz.jakarta.rs.LoggedFilter.RESOURCE_CLASS; +import static com.chavaillaz.jakarta.rs.LoggedFilter.RESOURCE_METHOD; +import static com.chavaillaz.jakarta.rs.LoggedFilter.RESPONSE_BODY; +import static com.chavaillaz.jakarta.rs.LoggedFilter.RESPONSE_STATUS; +import static jakarta.ws.rs.core.HttpHeaders.CONTENT_TYPE; +import static jakarta.ws.rs.core.MediaType.TEXT_PLAIN_TYPE; +import static java.lang.Integer.parseInt; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; + +import java.net.URISyntaxException; + +import jakarta.ws.rs.container.ResourceInfo; +import jakarta.ws.rs.ext.Providers; +import org.apache.commons.io.IOUtils; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.config.Configuration; +import org.apache.logging.log4j.core.config.LoggerConfig; +import org.jboss.resteasy.core.Headers; +import org.jboss.resteasy.core.interception.jaxrs.ContainerResponseContextImpl; +import org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext; +import org.jboss.resteasy.mock.MockHttpRequest; +import org.jboss.resteasy.mock.MockHttpResponse; +import org.jboss.resteasy.plugins.providers.DefaultTextPlain; +import org.jboss.resteasy.specimpl.BuiltResponse; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.MDC; + +@ExtendWith(MockitoExtension.class) +@Logged(requestBody = true, responseBody = true) +class LoggedFilterTest { + + private static final InMemoryAppender LIST_APPENDER = InMemoryAppender.createDefaultAppender(); + private static final String INPUT = "input"; + private static final String OUTPUT = "output"; + + @Mock + ResourceInfo resourceInfo; + + @Mock + Providers providers; + + @InjectMocks + LoggedFilter requestLoggingFilter; + + @BeforeAll + static void registerListAppender() { + LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); + Configuration configuration = loggerContext.getConfiguration(); + LoggerConfig rootLoggerConfig = configuration.getLoggerConfig(""); + rootLoggerConfig.addAppender(LIST_APPENDER, Level.ALL, null); + } + + @BeforeEach + void setupTest() { + MDC.clear(); + LIST_APPENDER.getMessages().clear(); + LIST_APPENDER.start(); + // Returns this method and class as the resource matched by the queries in tests + doReturn(new Object() {}.getClass().getEnclosingMethod()).when(resourceInfo).getResourceMethod(); + doReturn(this.getClass()).when(resourceInfo).getResourceClass(); + } + + @Test + @DisplayName("Check filter on request sets up MDC fields") + void filterRequestCheckMdc() throws URISyntaxException { + // Given + PreMatchContainerRequestContext requestContext = getRequestContext(); + + // When + requestLoggingFilter.filter(requestContext); + + // Then + assertNotNull(MDC.get(REQUEST_ID)); + assertEquals(requestContext.getUriInfo().getPath(), MDC.get(REQUEST_URI)); + assertEquals(requestContext.getMethod(), MDC.get(REQUEST_METHOD)); + assertEquals(getClass().getSimpleName(), MDC.get(RESOURCE_CLASS)); + assertEquals("setupTest", MDC.get(RESOURCE_METHOD)); + } + + @Test + @DisplayName("Check filter on request and response writes log with MDC fields") + void filterResponseCheckLog() throws Exception { + // Given + PreMatchContainerRequestContext requestContext = getRequestContext(); + ContainerResponseContextImpl responseContext = getResponseContext(requestContext); + doReturn(new DefaultTextPlain()).when(providers).getMessageBodyWriter(any(), any(), any(), any()); + + // When + requestLoggingFilter.filter(requestContext); + requestLoggingFilter.filter(requestContext, responseContext); + + // Then + assertNotNull(getLoggedMdc(REQUEST_ID)); + assertEquals(requestContext.getUriInfo().getPath(), getLoggedMdc(REQUEST_URI)); + assertEquals(requestContext.getMethod(), getLoggedMdc(REQUEST_METHOD)); + assertEquals(getClass().getSimpleName(), getLoggedMdc(RESOURCE_CLASS)); + assertEquals("setupTest", getLoggedMdc(RESOURCE_METHOD)); + assertEquals(responseContext.getHttpResponse().getStatus(), parseInt(getLoggedMdc(RESPONSE_STATUS))); + assertNotNull(getLoggedMdc(DURATION)); + assertEquals(INPUT, getLoggedMdc(REQUEST_BODY)); + assertEquals(OUTPUT, getLoggedMdc(RESPONSE_BODY)); + } + + private PreMatchContainerRequestContext getRequestContext() throws URISyntaxException { + MockHttpRequest request = MockHttpRequest.create("POST", "example.company.com/service"); + request.setInputStream(IOUtils.toInputStream(INPUT, UTF_8)); + request.contentType(TEXT_PLAIN_TYPE); + return new PreMatchContainerRequestContext(request); + } + + private ContainerResponseContextImpl getResponseContext(PreMatchContainerRequestContext request) { + int responseStatus = 200; + Headers headers = new Headers<>(); + headers.add(CONTENT_TYPE, TEXT_PLAIN_TYPE.toString()); + MockHttpResponse httpResponse = new MockHttpResponse(); + httpResponse.setStatus(responseStatus); + BuiltResponse builtResponse = new BuiltResponse(responseStatus, headers, OUTPUT, null); + return new ContainerResponseContextImpl(request.getHttpRequest(), httpResponse, builtResponse); + } + + private String getLoggedMdc(String key) { + return LIST_APPENDER.getMessages().stream() + .filter(log -> log.getMessage().getFormattedMessage().startsWith("Processed")) + .map(LogEvent::getContextData) + .map(mdc -> mdc.getValue(key)) + .map(Object::toString) + .findFirst() + .orElse(null); + } + +} + diff --git a/src/test/resources/log4j2.xml b/src/test/resources/log4j2.xml new file mode 100644 index 0000000..a988145 --- /dev/null +++ b/src/test/resources/log4j2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file