Home >Java >javaTutorial >How Can I Centrally Log Spring Boot REST API Requests, Responses, and Exceptions?

How Can I Centrally Log Spring Boot REST API Requests, Responses, and Exceptions?

Barbara Streisand
Barbara StreisandOriginal
2024-11-23 13:48:16925browse

How Can I Centrally Log Spring Boot REST API Requests, Responses, and Exceptions?

Logging Requests and Responses with Exceptions Centrally in Spring Boot

When developing REST APIs, it's crucial to capture comprehensive logs of all requests and responses, including input parameters, class methods, and exceptions. This centralized logging enables quick debugging and auditing.

Best Practice Approach

Spring Boot offers an effective and straightforward solution for this task: the Actuator module. Actuator provides an endpoint (/trace or /actuator/httptrace) that logs the last 100 HTTP requests by default.

Customization

To log every request and tailor the endpoint to your specific needs, you can:

  • Add the spring-boot-starter-actuator dependency to your project.
  • Whitelist the desired endpoints (e.g., /trace or /api/**) to ensure they're logged.
  • Optionally, configure security settings to protect access to these endpoints.

Additional Considerations

Other hosting providers, such as Heroku, often provide request logging as a service, eliminating the need for custom code.

Example

To configure Actuator for request and response logging in a Spring Boot application:

    dependencies {
        implementation 'org.springframework.boot:spring-boot-starter-actuator'
    }

    # Security configuration (optional)
    security {
        httpBasic {}
        headers {
            hsts {
                enabled = true
                maxAge = 31536000L  # 1 year
            }
        }
    }

Output

The /trace endpoint produces a JSON response similar to the desired format:

{
  "timestamp": 1656211869816,
  "message": "Successful request",
  "path": "/api/users/1",
  "method": "GET",
  "status": 200,
  "timeTaken": 1397
}

In case of an exception:

{
  "timestamp": 1656211972854,
  "message": "UserNotFoundException: User with id 9999 not found",
  "path": "/api/users/9999",
  "method": "GET",
  "status": 404,
  "timeTaken": 2063,
  "exception": "UserNotFoundException",
  "error": "User with id 9999 not found"
}

The above is the detailed content of How Can I Centrally Log Spring Boot REST API Requests, Responses, and Exceptions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn