diff --git a/gunicorn-logging-extension/pyproject.toml b/gunicorn-logging-extension/pyproject.toml index 8368f1e..eeda38d 100644 --- a/gunicorn-logging-extension/pyproject.toml +++ b/gunicorn-logging-extension/pyproject.toml @@ -24,6 +24,8 @@ classifiers = [ ] dependencies = ["gunicorn", "systemd_python"] +[project.optional-dependencies] +aiohttp = ["aiohttp"] [project.urls] Documentation = "https://github.com/unknown/gunicorn-logging-extension#readme" Issues = "https://github.com/unknown/gunicorn-logging-extension/issues" @@ -34,6 +36,7 @@ path = "src/gunicorn_logging_extension/__init__.py" [tool.hatch.build] directory = "../dist" + [tool.hatch.envs.default] dependencies = ["coverage[toml]>=6.5", "pytest"] [tool.hatch.envs.default.scripts] diff --git a/gunicorn-logging-extension/src/gunicorn_logging_extension/aiohttp.py b/gunicorn-logging-extension/src/gunicorn_logging_extension/aiohttp.py new file mode 100644 index 0000000..3aeccd9 --- /dev/null +++ b/gunicorn-logging-extension/src/gunicorn_logging_extension/aiohttp.py @@ -0,0 +1,32 @@ +from aiohttp.abc import AbstractAccessLogger +from aiohttp.web_request import BaseRequest +from aiohttp.web_response import StreamResponse +from . import REDIRECT_CODES + +class AccessLogger(AbstractAccessLogger): + + def log(self, request: BaseRequest, response: StreamResponse, time: float): + level = self.logger.info + if response.status >= 400: + level = self.logger.warning + elif response.status >= 500: + level = self.logger.error + extra = dict( + METHOD=request.method, + PATH=request.rel_url, + QUERY=request.query_string, + PROTOCOL=request.scheme, + TIME=time, + STATUS_CODE=response.status_code, + REMOTE=request.remote, + LENGTH=response.content_length, + ) + if request.headers.get("Referer", False): + extra["REFERER"] = request.headers.get("Referer") + if request.headers.get("user-agent", False): + extra["USER_AGENT"] = request.headers.get("user-agent") + location="" + if response.status_code in REDIRECT_CODES: + extra["LOCATION"] = request.headers.get("location") + location = f" -> {extra["LOCATION"]}" + level(f"Access({response.status}) {request.method} {request.rel_url}{}", extra=extra)