sanic/examples/log_request_id.py

76 lines
1.6 KiB
Python
Raw Normal View History

import logging
import aiotask_context as context
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 = context.get("X-Request-ID")
except ValueError:
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):
2021-03-10 09:19:38 +00:00
request_id = request.id
context.set("X-Request-ID", 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):
2021-03-10 09:19:38 +00:00
log.debug("X-Request-ID: %s", context.get("X-Request-ID"))
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):
loop.set_task_factory(context.task_factory)
2021-03-10 09:19:38 +00:00
if __name__ == "__main__":
app.run(port=9999, debug=True)