sanic/examples/log_request_id.py

75 lines
1.6 KiB
Python
Raw Normal View History

import logging
from contextvars import ContextVar
2021-03-10 09:19:38 +00:00
from sanic import Sanic, response
log = logging.getLogger(__name__)
class RequestIdFilter(logging.Filter):
def filter(self, record):
2021-03-10 09:19:38 +00:00
try:
record.request_id = app.ctx.request_id.get(None) or "n/a"
except AttributeError:
2021-03-10 09:19:38 +00:00
record.request_id = "n/a"
return True
LOG_SETTINGS = {
2021-03-10 09:19:38 +00:00
"version": 1,
"disable_existing_loggers": False,
"handlers": {
"console": {
"class": "logging.StreamHandler",
"level": "DEBUG",
"formatter": "default",
"filters": ["requestid"],
},
},
2021-03-10 09:19:38 +00:00
"filters": {
"requestid": {
"()": RequestIdFilter,
},
},
2021-03-10 09:19:38 +00:00
"formatters": {
"default": {
"format": "%(asctime)s %(levelname)s %(name)s:%(lineno)d %(request_id)s | %(message)s",
},
},
2021-03-10 09:19:38 +00:00
"loggers": {
"": {"level": "DEBUG", "handlers": ["console"], "propagate": True},
},
}
app = Sanic(__name__, log_config=LOG_SETTINGS)
2021-03-10 09:19:38 +00:00
@app.on_request
async def set_request_id(request):
request.app.ctx.request_id.set(request.id)
2021-03-10 09:19:38 +00:00
log.info(f"Setting {request.id=}")
@app.on_response
async def set_request_header(request, response):
response.headers["X-Request-ID"] = request.id
@app.route("/")
async def test(request):
log.debug("X-Request-ID: %s", request.id)
2021-03-10 09:19:38 +00:00
log.info("Hello from test!")
return response.json({"test": True})
2021-03-10 09:19:38 +00:00
@app.before_server_start
def setup(app, loop):
app.ctx.request_id = ContextVar("request_id")
2021-03-10 09:19:38 +00:00
if __name__ == "__main__":
app.run(port=9999, debug=True)