fastapi-gae-logging 0.0.1__py3-none-any.whl

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.
@@ -0,0 +1,5 @@
1
+ from .fastapi_gae_logging import FastAPIGAELoggingHandler
2
+
3
+ __all__ = [
4
+ "FastAPIGAELoggingHandler",
5
+ ]
@@ -0,0 +1,212 @@
1
+ import logging
2
+ import time
3
+ import contextvars
4
+ import os
5
+ import re
6
+ from typing import Optional, Dict, Any
7
+ from fastapi import FastAPI
8
+ from starlette.exceptions import HTTPException
9
+ from starlette.types import ASGIApp, Receive, Scope, Send
10
+ from starlette.responses import Response
11
+ from starlette.requests import Request
12
+ from google.cloud.logging_v2.handlers import CloudLoggingHandler
13
+ from google.cloud.logging_v2 import Resource, Logger
14
+
15
+
16
+ gae_request_context = contextvars.ContextVar('gae_request_context', default={
17
+ 'trace': None,
18
+ 'start_time': None,
19
+ 'max_log_level': logging.NOTSET
20
+ })
21
+
22
+
23
+ class LogInterceptor(logging.Filter):
24
+ """
25
+ Logging filter to group logs of a given request and set the maximum log level
26
+ lifecycle for an ASGI app deployed in Google App Engine, using context management and trace.
27
+ for its lifecycle in an ASGI app deployed in Google App Engine, using context management and trace.
28
+ """
29
+
30
+ def filter(self, record: logging.LogRecord) -> bool:
31
+ """
32
+ Filter log records based on the maximum log level set in the request lifecycle.
33
+
34
+ Args:
35
+ record (logging.LogRecord): The log record to filter.
36
+
37
+ Returns:
38
+ bool: True to allow the log record, False to suppress it.
39
+ """
40
+
41
+ gae_request_context_data = gae_request_context.get()
42
+ max_log_level = gae_request_context_data['max_log_level']
43
+
44
+ if record.levelno > max_log_level:
45
+ gae_request_context_data['max_log_level'] = record.levelno
46
+
47
+ trace = gae_request_context_data['trace']
48
+
49
+ if trace:
50
+ split_header = trace.split('/', 1)
51
+ record._trace = f"projects/{os.environ['GOOGLE_CLOUD_PROJECT']}/traces/{split_header[0]}"
52
+ record._span_id = re.findall(r'^\w+', split_header[1])[0]
53
+
54
+ return True
55
+
56
+
57
+ class GAERequestLogger:
58
+ LOG_LEVEL_TO_SEVERITY: Dict[int, str] = {
59
+ logging.NOTSET: 'DEFAULT',
60
+ logging.DEBUG: 'DEBUG',
61
+ logging.INFO: 'INFO',
62
+ logging.WARNING: 'WARNING',
63
+ logging.ERROR: 'ERROR',
64
+ logging.CRITICAL: 'CRITICAL',
65
+ }
66
+
67
+ def __init__(self, logger: Logger, resource: Resource) -> None:
68
+ """
69
+ Initialize the GAERequestLogger.
70
+
71
+ Args:
72
+ logger (Logger): The Google Cloud Logger instance to log requests.
73
+ resource (Resource): The resource associated with the logger.
74
+ """
75
+ self.logger = logger
76
+ self.resource = resource
77
+
78
+ def _log_level_to_severity(self, log_level: int) -> str:
79
+ """
80
+ Convert Python logging level to Cloud Logging severity.
81
+
82
+ Args:
83
+ log_level (int): The logging level.
84
+
85
+ Returns:
86
+ str: The corresponding Cloud Logging severity.
87
+ """
88
+ return self.LOG_LEVEL_TO_SEVERITY.get(log_level, self.LOG_LEVEL_TO_SEVERITY[logging.NOTSET])
89
+
90
+ async def emit_request_log(self, request: Request, response: Response) -> None:
91
+ """
92
+ Log structured data after handling the request and right before returning a response.
93
+ Severity of log is determined based on the maximum log level
94
+ captured in the request state context.
95
+
96
+ Args:
97
+ request: The request object.
98
+ response: The response object.
99
+ """
100
+ gae_request_context_data = gae_request_context.get()
101
+ trace = gae_request_context_data['trace']
102
+
103
+ if not trace:
104
+ return
105
+
106
+ severity = self._log_level_to_severity(log_level=gae_request_context_data['max_log_level'])
107
+
108
+ http_request = {
109
+ 'requestMethod': request.method,
110
+ 'requestUrl': str(request.url),
111
+ 'status': response.status_code,
112
+ 'userAgent': request.headers.get('User-Agent'),
113
+ 'responseSize': response.headers.get('Content-Length'),
114
+ 'latency': f'{(time.time() - gae_request_context_data["start_time"]):.6f}s',
115
+ 'remoteIp': request.client.host
116
+ }
117
+
118
+ payload = {}
119
+ if request.method in ('POST', 'PUT', 'PATCH', 'DELETE'):
120
+ try:
121
+ payload = await request.json()
122
+ except Exception:
123
+ pass
124
+
125
+ self.logger.log_struct(
126
+ info=payload,
127
+ resource=self.resource,
128
+ trace=f"projects/{os.environ['GOOGLE_CLOUD_PROJECT']}/traces/{trace.split('/', 1)[0]}",
129
+ http_request=http_request,
130
+ severity=severity
131
+ )
132
+
133
+
134
+ class FastAPIGAELoggingMiddleware:
135
+ """
136
+ Custom middleware to set up request start time and emit logs after request completion.
137
+ Specifically designed for FastAPI applications deployed on Google App Engine.
138
+ """
139
+
140
+ def __init__(self, app: ASGIApp, logger: GAERequestLogger):
141
+ self.app = app
142
+ self.logger = logger
143
+
144
+ async def __call__(self, scope: Scope, receive: Receive, send: Send):
145
+ if scope["type"] == "http":
146
+ request = Request(scope, receive=receive)
147
+
148
+ gae_request_context.set({
149
+ 'trace': request.headers.get('X-Cloud-Trace-Context'),
150
+ 'start_time': time.time(),
151
+ 'max_log_level': logging.NOTSET
152
+ })
153
+
154
+ response = Response(status_code=500)
155
+
156
+ async def send_wrapper(message: Dict[str, Any]) -> None:
157
+ if message["type"] == "http.response.start":
158
+ response.status_code = message["status"]
159
+ elif message["type"] == "http.response.body":
160
+ response.body = message.get("body", b"")
161
+ await send(message)
162
+
163
+ try:
164
+ await self.app(scope, receive, send_wrapper)
165
+ except Exception as e:
166
+ if not isinstance(e, HTTPException):
167
+ logging.exception(e)
168
+ raise e
169
+ finally:
170
+ await self.logger.emit_request_log(request, response)
171
+
172
+
173
+ class FastAPIGAELoggingHandler(CloudLoggingHandler):
174
+ """
175
+ Custom Cloud Logging handler for FastAPI applications deployed in Google App Engine.
176
+ Groups logs coming from the same request lifecycle and propagates the maximum log level
177
+ throughout the request lifecycle using middleware and context management.
178
+ """
179
+
180
+ REQUEST_LOGGER_SUFFIX: str = '-request-logger'
181
+
182
+ def __init__(
183
+ self,
184
+ app: FastAPI,
185
+ request_logger_name: Optional[str] = None,
186
+ *args, **kwargs
187
+ ) -> None:
188
+ """
189
+ Initialize the handler.
190
+
191
+ Args:
192
+ app (FastAPI): The FastAPI application instance.
193
+ request_logger_name (Optional[str]): The name of the Cloud Logging logger to use for request logs.
194
+ Defaults to the Google Cloud Project ID with '-request-logger' suffix.
195
+ *args: Additional arguments to pass to the superclass constructor.
196
+ Any argument you would pass to CloudLoggingHandler.
197
+ **kwargs: Additional keyword arguments to pass to the superclass constructor.
198
+ Any keyword argument you would pass to CloudLoggingHandler.
199
+ """
200
+ super().__init__(*args, **kwargs)
201
+ self.app = app
202
+ self.app.add_middleware(
203
+ middleware_class=FastAPIGAELoggingMiddleware,
204
+ logger=GAERequestLogger(
205
+ logger=self.client.logger(
206
+ name=request_logger_name or f"{os.getenv('GOOGLE_CLOUD_PROJECT')}{self.REQUEST_LOGGER_SUFFIX}",
207
+ resource=self.resource
208
+ ),
209
+ resource=self.resource
210
+ )
211
+ )
212
+ self.addFilter(LogInterceptor())
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Chris Karvouniaris
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,112 @@
1
+ Metadata-Version: 2.1
2
+ Name: fastapi-gae-logging
3
+ Version: 0.0.1
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
+ Home-page: https://github.com/chrisK824/fastapi-gae-logging
6
+ Author: Chris Karvouniaris
7
+ Author-email: christos.karvouniaris247@gmail.com
8
+ License: MIT
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.7
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: fastapi >=0.112.2
15
+ Requires-Dist: google-cloud-logging >=3.10.0
16
+
17
+ # fastapi-gae-logging
18
+ Custom Cloud Logging handler for FastAPI applications deployed in Google App Engine.
19
+ Groups logs coming from the same request lifecycle and propagates the maximum log level throughout the request lifecycle using middleware and context management.
20
+
21
+ ## Install
22
+ `pip install fastapi-gae-logging`
23
+
24
+ ## Features:
25
+
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
+ - **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
+
29
+ ## API
30
+ - Custom Cloud Logging Handler to use with official library `google-cloud-logging`: `FastAPIGAELoggingHandler`
31
+
32
+
33
+ ## Example
34
+
35
+ ```python
36
+ from fastapi import FastAPI
37
+ from fastapi.responses import JSONResponse
38
+ from fastapi.exceptions import HTTPException
39
+ import logging
40
+ import os
41
+
42
+
43
+ app = FastAPI()
44
+
45
+ if os.getenv('GAE_ENV', '').startswith('standard'):
46
+ import google.cloud.logging
47
+ from google.cloud.logging_v2.handlers import setup_logging
48
+ from fastapi_gae_logging import FastAPIGAELoggingHandler
49
+
50
+ client = google.cloud.logging.Client()
51
+ gae_log_handler = FastAPIGAELoggingHandler(app=app, client=client)
52
+ setup_logging(handler=gae_log_handler)
53
+
54
+
55
+ logging.getLogger().setLevel(logging.DEBUG)
56
+
57
+
58
+ @app.get("/info")
59
+ def info():
60
+ logging.debug("this is a debug")
61
+ logging.info("this is an info")
62
+ return JSONResponse(
63
+ content={
64
+ "message": "info"
65
+ }
66
+ )
67
+
68
+
69
+ @app.get("/warning")
70
+ async def warning():
71
+ logging.debug("this is a debug")
72
+ logging.info("this is an info")
73
+ logging.warning("this is a warning")
74
+ return JSONResponse(
75
+ content={
76
+ "message": "warning"
77
+ }
78
+ )
79
+
80
+
81
+ @app.get("/error")
82
+ def error():
83
+ logging.debug("this is a debug")
84
+ logging.info("this is an info")
85
+ logging.warning("this is a warning")
86
+ logging.error("this is an error")
87
+ return JSONResponse(
88
+ content={
89
+ "message": "error"
90
+ }
91
+ )
92
+
93
+
94
+ @app.get("/exception")
95
+ def exception():
96
+ logging.debug("this is a debug")
97
+ logging.info("this is an info")
98
+ logging.error("this is an error")
99
+ raise ValueError("This is a value error")
100
+
101
+
102
+ @app.get("/http_exception")
103
+ def http_exception():
104
+ logging.debug("this is an debug")
105
+ logging.info("this is an info")
106
+ raise HTTPException(
107
+ status_code=404,
108
+ detail={
109
+ "error": "Resource not found"
110
+ }
111
+ )
112
+ ```
@@ -0,0 +1,7 @@
1
+ fastapi_gae_logging/__init__.py,sha256=hbDGnT8MK466kQkh2bLH3V7-UYv_Us-C664j6qQePtc,105
2
+ fastapi_gae_logging/fastapi_gae_logging.py,sha256=T2WVX6sRoFrCGph1oBUErhDqkxCzf-7jv5CH2VVBAsA,7595
3
+ fastapi_gae_logging-0.0.1.dist-info/LICENSE,sha256=choQHlcoU1oY_qjpDr5JCxI9BnV0arIpimC09MoOatA,1075
4
+ fastapi_gae_logging-0.0.1.dist-info/METADATA,sha256=h5dFOUO--lBr9uNGlz8UYxRxLYv6l4RYRSx1_RwMLYc,3386
5
+ fastapi_gae_logging-0.0.1.dist-info/WHEEL,sha256=Mdi9PDNwEZptOjTlUcAth7XJDFtKrHYaQMPulZeBCiQ,91
6
+ fastapi_gae_logging-0.0.1.dist-info/top_level.txt,sha256=PDYheatqYRcjvuB1LYVrCrGxhR5j9QHyCGJXg2NZseA,20
7
+ fastapi_gae_logging-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (73.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ fastapi_gae_logging