structlog-gcp icon indicating copy to clipboard operation
structlog-gcp copied to clipboard

HTTP request processor

Open multani opened this issue 1 year ago • 1 comments

This adds a new HTTP-specific processor that formats logs according to the HttpRequest Google Cloud Logging log format.

See: https://cloud.google.com/logging/docs/structured-logging#structured_logging_special_fields See: https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#httprequest

Fix: #32


This introduces:

  • A new class to represent the current HTTP Request. It maps to what GCP supports, but with specific attributes which are a bit more agnostic (size is a number, not a string, for instance.)
  • A new processor that "knows" how to convert the previous HTTP request object for logging

This can be used in different ways:

Either the user creates the HTTPRequest object itself and logs it directly:

def handler(request):
    r = HTTPRequest(method=request.method, ...)
    logger.info("new request coming", http_request=r)

Or this is implemented as part of a framework (inside WSGI or ASGI or framework-specific middleware for instance), in which case we can offer a dedicated adapter from the framework objects to the HTTPRequest format.

For this case, the pull request offers an adapter from Starlette request/response + a test with a basic Starlette middleware.

multani avatar Sep 21 '24 20:09 multani

@petemounce you may be interested by this: this implements something similar to what we discussed in #32

  • I reused part of the code you show me in #32 to write the Starlette middleware (I assume this is what you actually had in #32?)
  • This shows how the adapter from Starlette could be used. The plan would be to not ship the middleware itself, but proposed a simpler adapter that could be reused inside your own middleware.

multani avatar Sep 21 '24 20:09 multani