fastapi-gae-logging 0.0.1__tar.gz → 0.0.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: fastapi-gae-logging
3
- Version: 0.0.1
3
+ Version: 0.0.2
4
4
  Summary: Custom Cloud Logging handler for FastAPI applications deployed in Google App Engine. Groups logs coming from the same request lifecycle and propagates the maximum log level throughout the request lifecycle using middleware and context management.
5
5
  Home-page: https://github.com/chrisK824/fastapi-gae-logging
6
6
  Author: Chris Karvouniaris
@@ -12,7 +12,7 @@ Requires-Python: >=3.7
12
12
  Description-Content-Type: text/markdown
13
13
  License-File: LICENSE
14
14
  Requires-Dist: fastapi>=0.112.2
15
- Requires-Dist: google-cloud-logging>=3.10.0
15
+ Requires-Dist: google-cloud-logging>=3.11.2
16
16
 
17
17
  # fastapi-gae-logging
18
18
  Custom Cloud Logging handler for FastAPI applications deployed in Google App Engine.
@@ -25,6 +25,10 @@ Groups logs coming from the same request lifecycle and propagates the maximum lo
25
25
 
26
26
  - **Request Logs Grouping**: Groups logs coming from the same request lifecycle to ease out log analysis using the Google Cloud Log Explorer. Grouping logger name can be customised and it defaults to the Google Cloud Project ID with '-request-logger' as a suffix.
27
27
  - **Request Maximum Log Level propagation**: Propagates the maximum log level throughout the request lifecycle to ease out log searching based on severity of an issue.
28
+ - **Request Payload Logging** - More options to be exposed on that behaviour:
29
+ - In case the request contains a payload, then this is logged into the parent log of request grouped logs
30
+ - For now content type of payload is assumed to be a valid JSON, otherwise it is discarded. More to be supported later on.
31
+ - The payload is logged as a dictionary using the `google-cloud-logging`'s method for `log_struct`. Since that method is logging only dictionaries, any JSON valid payload that is not a dictionary is wrapped into a dummy keyword to constuct one. The dummy keyword looks like that: `<original_type_of_payload>__payload_wrapper` The original or virtual dictionary is logged with `log_struct` along with the parent log of request grouped logs and ends up in field `jsonPayload`.
28
32
 
29
33
  ## API
30
34
  - Custom Cloud Logging Handler to use with official library `google-cloud-logging`: `FastAPIGAELoggingHandler`
@@ -9,6 +9,10 @@ Groups logs coming from the same request lifecycle and propagates the maximum lo
9
9
 
10
10
  - **Request Logs Grouping**: Groups logs coming from the same request lifecycle to ease out log analysis using the Google Cloud Log Explorer. Grouping logger name can be customised and it defaults to the Google Cloud Project ID with '-request-logger' as a suffix.
11
11
  - **Request Maximum Log Level propagation**: Propagates the maximum log level throughout the request lifecycle to ease out log searching based on severity of an issue.
12
+ - **Request Payload Logging** - More options to be exposed on that behaviour:
13
+ - In case the request contains a payload, then this is logged into the parent log of request grouped logs
14
+ - For now content type of payload is assumed to be a valid JSON, otherwise it is discarded. More to be supported later on.
15
+ - The payload is logged as a dictionary using the `google-cloud-logging`'s method for `log_struct`. Since that method is logging only dictionaries, any JSON valid payload that is not a dictionary is wrapped into a dummy keyword to constuct one. The dummy keyword looks like that: `<original_type_of_payload>__payload_wrapper` The original or virtual dictionary is logged with `log_struct` along with the parent log of request grouped logs and ends up in field `jsonPayload`.
12
16
 
13
17
  ## API
14
18
  - Custom Cloud Logging Handler to use with official library `google-cloud-logging`: `FastAPIGAELoggingHandler`
@@ -3,6 +3,7 @@ import time
3
3
  import contextvars
4
4
  import os
5
5
  import re
6
+ import json
6
7
  from typing import Optional, Dict, Any
7
8
  from fastapi import FastAPI
8
9
  from starlette.exceptions import HTTPException
@@ -119,9 +120,14 @@ class GAERequestLogger:
119
120
  if request.method in ('POST', 'PUT', 'PATCH', 'DELETE'):
120
121
  try:
121
122
  payload = await request.json()
122
- except Exception:
123
+ except json.JSONDecodeError:
123
124
  pass
124
125
 
126
+ if not isinstance(payload, dict):
127
+ payload = {
128
+ f"{type(payload).__name__}_payload_wrapper": payload
129
+ }
130
+
125
131
  self.logger.log_struct(
126
132
  info=payload,
127
133
  resource=self.resource,
@@ -143,7 +149,17 @@ class FastAPIGAELoggingMiddleware:
143
149
 
144
150
  async def __call__(self, scope: Scope, receive: Receive, send: Send):
145
151
  if scope["type"] == "http":
146
- request = Request(scope, receive=receive)
152
+
153
+ # https://stackoverflow.com/questions/64115628/get-starlette-request-body-in-the-middleware-context
154
+ # Mock function that returns a cached copy of the request
155
+ # so that anyone can ask for the body aftewards from the request object
156
+
157
+ receive_cached_ = await receive()
158
+
159
+ async def receive_cached():
160
+ return receive_cached_
161
+
162
+ request = Request(scope, receive=receive_cached)
147
163
 
148
164
  gae_request_context.set({
149
165
  'trace': request.headers.get('X-Cloud-Trace-Context'),
@@ -151,9 +167,12 @@ class FastAPIGAELoggingMiddleware:
151
167
  'max_log_level': logging.NOTSET
152
168
  })
153
169
 
170
+ # start with the default response in case of generic error
154
171
  response = Response(status_code=500)
155
172
 
156
- async def send_wrapper(message: Dict[str, Any]) -> None:
173
+ # intercept the sent message to get the response status and body
174
+ # for later use
175
+ async def send_spoof_wrapper(message: Dict[str, Any]) -> None:
157
176
  if message["type"] == "http.response.start":
158
177
  response.status_code = message["status"]
159
178
  elif message["type"] == "http.response.body":
@@ -161,7 +180,7 @@ class FastAPIGAELoggingMiddleware:
161
180
  await send(message)
162
181
 
163
182
  try:
164
- await self.app(scope, receive, send_wrapper)
183
+ await self.app(scope, receive_cached, send_spoof_wrapper)
165
184
  except Exception as e:
166
185
  if not isinstance(e, HTTPException):
167
186
  logging.exception(e)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: fastapi-gae-logging
3
- Version: 0.0.1
3
+ Version: 0.0.2
4
4
  Summary: Custom Cloud Logging handler for FastAPI applications deployed in Google App Engine. Groups logs coming from the same request lifecycle and propagates the maximum log level throughout the request lifecycle using middleware and context management.
5
5
  Home-page: https://github.com/chrisK824/fastapi-gae-logging
6
6
  Author: Chris Karvouniaris
@@ -12,7 +12,7 @@ Requires-Python: >=3.7
12
12
  Description-Content-Type: text/markdown
13
13
  License-File: LICENSE
14
14
  Requires-Dist: fastapi>=0.112.2
15
- Requires-Dist: google-cloud-logging>=3.10.0
15
+ Requires-Dist: google-cloud-logging>=3.11.2
16
16
 
17
17
  # fastapi-gae-logging
18
18
  Custom Cloud Logging handler for FastAPI applications deployed in Google App Engine.
@@ -25,6 +25,10 @@ Groups logs coming from the same request lifecycle and propagates the maximum lo
25
25
 
26
26
  - **Request Logs Grouping**: Groups logs coming from the same request lifecycle to ease out log analysis using the Google Cloud Log Explorer. Grouping logger name can be customised and it defaults to the Google Cloud Project ID with '-request-logger' as a suffix.
27
27
  - **Request Maximum Log Level propagation**: Propagates the maximum log level throughout the request lifecycle to ease out log searching based on severity of an issue.
28
+ - **Request Payload Logging** - More options to be exposed on that behaviour:
29
+ - In case the request contains a payload, then this is logged into the parent log of request grouped logs
30
+ - For now content type of payload is assumed to be a valid JSON, otherwise it is discarded. More to be supported later on.
31
+ - The payload is logged as a dictionary using the `google-cloud-logging`'s method for `log_struct`. Since that method is logging only dictionaries, any JSON valid payload that is not a dictionary is wrapped into a dummy keyword to constuct one. The dummy keyword looks like that: `<original_type_of_payload>__payload_wrapper` The original or virtual dictionary is logged with `log_struct` along with the parent log of request grouped logs and ends up in field `jsonPayload`.
28
32
 
29
33
  ## API
30
34
  - Custom Cloud Logging Handler to use with official library `google-cloud-logging`: `FastAPIGAELoggingHandler`
@@ -0,0 +1,2 @@
1
+ fastapi>=0.112.2
2
+ google-cloud-logging>=3.11.2
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
2
2
 
3
3
  setup(
4
4
  name="fastapi-gae-logging",
5
- version="0.0.1",
5
+ version="0.0.2",
6
6
  description="Custom Cloud Logging handler for FastAPI applications deployed in Google App Engine. \
7
7
  Groups logs coming from the same request lifecycle and propagates the maximum log level \
8
8
  throughout the request lifecycle using middleware and context management.",
@@ -14,7 +14,7 @@ setup(
14
14
  packages=find_packages(),
15
15
  install_requires=[
16
16
  "fastapi>=0.112.2",
17
- "google-cloud-logging>=3.10.0",
17
+ "google-cloud-logging>=3.11.2",
18
18
  ],
19
19
  python_requires=">=3.7",
20
20
  license="MIT",
@@ -1,2 +0,0 @@
1
- fastapi>=0.112.2
2
- google-cloud-logging>=3.10.0