Skip to content

Commit 4a4babd

Browse files
committed
added option to opt out for logging payload; updated readme with absolute image addresses to fix render in pypi
1 parent 0a70f98 commit 4a4babd

File tree

3 files changed

+19
-18
lines changed

3 files changed

+19
-18
lines changed

README.md

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -116,14 +116,14 @@ def post_payload(payload: Any = Body(None)):
116116
## How it looks in Google Cloud Log Explorer
117117

118118
### Logger selection
119-
![alt text](<logger_selection.jpg>)
119+
![alt text](https://github.com/chrisK824/fastapi-gae-logging/raw/main/logger_selection.jpg)
120120

121121
### Groupped logs with propagated log severity to the parent log
122122

123-
![alt text](<groupped_logs.jpg>)
123+
![alt text](https://github.com/chrisK824/fastapi-gae-logging/raw/main/groupped_logs.jpg)
124124

125125
### Grouped logs in request with payload
126-
![alt text](<request_with_payload.jpg>)
126+
![alt text](https://github.com/chrisK824/fastapi-gae-logging/raw/main/request_with_payload.jpg)
127127

128128
## Dependencies
129129
This tool is built upon the following packages:
@@ -139,8 +139,3 @@ This tool is built upon the following packages:
139139
- **Cloud Logging**: Utilizes Google Cloud Logging to group logs by request and propagate the maximum log level, enhancing observability and troubleshooting.
140140
- **Structured Logging**: Parent log of the request-response lifecycle is structured and sent to Google Cloud Logging with additional context, such as the request method, URL, and user agent after the request has been processed and served.
141141

142-
143-
## Roadmap
144-
- Allow for opting out of the dictionary enforcement of logged payload.
145-
- Allow for opting out of request payload logging at all.
146-
- Explore other fields in Google Cloud Logs. Investigate and consider utilizing additional fields available in Google Cloud Logs that may allow for more goodies.

fastapi_gae_logging/fastapi_gae_logging.py

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ class GAERequestLogger:
6565
logging.CRITICAL: 'CRITICAL',
6666
}
6767

68-
def __init__(self, logger: Logger, resource: Resource) -> None:
68+
def __init__(self, logger: Logger, resource: Resource, log_payload: bool = True) -> None:
6969
"""
7070
Initialize the GAERequestLogger.
7171
@@ -75,6 +75,7 @@ def __init__(self, logger: Logger, resource: Resource) -> None:
7575
"""
7676
self.logger = logger
7777
self.resource = resource
78+
self.log_payload = log_payload
7879

7980
def _log_level_to_severity(self, log_level: int) -> str:
8081
"""
@@ -117,16 +118,19 @@ async def emit_request_log(self, request: Request, response: Response) -> None:
117118
}
118119

119120
payload = {}
120-
if request.method in ('POST', 'PUT', 'PATCH', 'DELETE'):
121+
122+
if self.log_payload and request.method in {'POST', 'PUT', 'PATCH', 'DELETE'}:
121123
try:
122124
payload = await request.json()
123125
except json.JSONDecodeError:
124-
pass
125-
126-
if not isinstance(payload, dict):
127-
payload = {
128-
f"{type(payload).__name__}_payload_wrapper": payload
129-
}
126+
logging.warning("Failed to decode request payload as JSON, skipping logging.")
127+
except Exception as e:
128+
logging.error(f"Unexpected error while logging payload: {e}")
129+
else:
130+
if not isinstance(payload, dict):
131+
payload = {
132+
f"{type(payload).__name__}_payload_wrapper": payload
133+
}
130134

131135
self.logger.log_struct(
132136
info=payload,
@@ -202,6 +206,7 @@ def __init__(
202206
self,
203207
app: FastAPI,
204208
request_logger_name: Optional[str] = None,
209+
log_payload: bool = True,
205210
*args, **kwargs
206211
) -> None:
207212
"""
@@ -225,7 +230,8 @@ def __init__(
225230
name=request_logger_name or f"{os.getenv('GOOGLE_CLOUD_PROJECT')}{self.REQUEST_LOGGER_SUFFIX}",
226231
resource=self.resource
227232
),
228-
resource=self.resource
233+
resource=self.resource,
234+
log_payload=log_payload
229235
)
230236
)
231237
self.addFilter(LogInterceptor())

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
setup(
44
name="fastapi-gae-logging",
5-
version="0.0.3",
5+
version="0.0.4",
66
description="Custom Cloud Logging handler for FastAPI applications deployed in Google App Engine. \
77
Groups logs coming from the same request lifecycle and propagates the maximum log level \
88
throughout the request lifecycle using middleware and context management.",

0 commit comments

Comments
 (0)