fix exclude logging

This commit is contained in:
Robert Resch 2022-08-24 22:20:59 +02:00
parent 03c3f4a4df
commit 2282748d1a

View file

@ -20,67 +20,69 @@ class CustomEncoder(json.JSONEncoder):
return json.JSONEncoder.default(self, obj) return json.JSONEncoder.default(self, obj)
_EXCLUDE_FROM_LOGGING = ["base", "remove-bot", "remove-client", "restart-service"] _EXCLUDE_FROM_LOGGING = [
"/",
"/bot/remove/{did}",
"/client/remove/{resource}",
"/restart_{service}",
]
@web.middleware @web.middleware
async def log_all_requests(request: Request, handler: Handler) -> StreamResponse: async def log_all_requests(request: Request, handler: Handler) -> StreamResponse:
if request.match_info.route.name not in _EXCLUDE_FROM_LOGGING: if (
to_log = { not request.match_info.route.resource
"request": { ) or request.match_info.route.resource.canonical in _EXCLUDE_FROM_LOGGING:
"method": request.method, return await handler(request)
"url": str(request.url),
"path": request.path, to_log = {
"query_string": request.query_string, "request": {
"headers": {h for h in request.headers.items()}, "method": request.method,
} "url": str(request.url),
"path": request.path,
"query_string": request.query_string,
"headers": {h for h in request.headers.items()},
"route_resource": request.match_info.route.resource.canonical,
}
}
try:
if request.content_length:
if request.content_type == "application/json":
to_log["request"]["body"] = await request.json()
else:
to_log["request"]["body"] = {h for h in await request.post()}
response = await handler(request)
if response is None:
_LOGGER.warning( # type:ignore[unreachable]
"Response was null!"
)
_LOGGER.warning(json.dumps(to_log, cls=CustomEncoder))
raise HTTPNoContent
to_log["response"] = {
"status": f"{response.status}",
} }
if request.match_info.route.resource: if isinstance(response, Response) and response.body:
to_log["request"][ assert response.text
"route_resource" if response.content_type == "application/json":
] = request.match_info.route.resource.canonical to_log["response"]["body"] = json.loads(response.text)
elif response.content_type.startswith("text"):
to_log["response"]["body"] = response.text
try: return response
if request.content_length:
if request.content_type == "application/json":
to_log["request"]["body"] = await request.json()
else:
to_log["request"]["body"] = {h for h in await request.post()}
response = await handler(request) except web.HTTPNotFound:
if response is None: _LOGGER.debug(f"Request path {request.raw_path} not found")
_LOGGER.warning( # type:ignore[unreachable] raise
"Response was null!"
)
_LOGGER.warning(json.dumps(to_log, cls=CustomEncoder))
raise HTTPNoContent
to_log["response"] = { except Exception:
"status": f"{response.status}", _LOGGER.exception(
} "An exception occurred in the logging middleware.", exc_info=True
)
raise
if isinstance(response, Response) and response.body: finally:
assert response.text _LOGGER.debug(json.dumps(to_log, cls=CustomEncoder))
if response.content_type == "application/json":
to_log["response"]["body"] = json.loads(response.text)
elif response.content_type.startswith("text"):
to_log["response"]["body"] = response.text
return response
except web.HTTPNotFound:
_LOGGER.debug(f"Request path {request.raw_path} not found")
raise
except Exception:
_LOGGER.exception(
"An exception occurred in the logging middleware.", exc_info=True
)
raise
finally:
_LOGGER.debug(json.dumps(to_log, cls=CustomEncoder))
else:
return await handler(request)