2017-08-29 21:05:57 +01:00
|
|
|
import logging
|
|
|
|
|
|
|
|
import aiotask_context as context
|
|
|
|
|
2021-03-10 09:19:38 +00:00
|
|
|
from sanic import Sanic, response
|
|
|
|
|
|
|
|
|
2017-08-29 21:05:57 +01:00
|
|
|
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"
|
2017-08-29 21:05:57 +01:00
|
|
|
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"],
|
2017-08-29 21:05:57 +01:00
|
|
|
},
|
|
|
|
},
|
2021-03-10 09:19:38 +00:00
|
|
|
"filters": {
|
|
|
|
"requestid": {
|
|
|
|
"()": RequestIdFilter,
|
2017-08-29 21:05:57 +01:00
|
|
|
},
|
|
|
|
},
|
2021-03-10 09:19:38 +00:00
|
|
|
"formatters": {
|
|
|
|
"default": {
|
|
|
|
"format": "%(asctime)s %(levelname)s %(name)s:%(lineno)d %(request_id)s | %(message)s",
|
2017-08-29 21:05:57 +01:00
|
|
|
},
|
|
|
|
},
|
2021-03-10 09:19:38 +00:00
|
|
|
"loggers": {
|
|
|
|
"": {"level": "DEBUG", "handlers": ["console"], "propagate": True},
|
|
|
|
},
|
2017-08-29 21:05:57 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
app = Sanic(__name__, log_config=LOG_SETTINGS)
|
|
|
|
|
|
|
|
|
2021-03-10 09:19:38 +00:00
|
|
|
@app.on_request
|
2017-08-29 21:05:57 +01:00
|
|
|
async def set_request_id(request):
|
2021-03-10 09:19:38 +00:00
|
|
|
request_id = request.id
|
2017-08-29 21:05:57 +01:00
|
|
|
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
|
2017-08-29 21:05:57 +01:00
|
|
|
|
|
|
|
|
|
|
|
@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!")
|
2017-08-29 21:05:57 +01:00
|
|
|
return response.json({"test": True})
|
|
|
|
|
|
|
|
|
2021-03-10 09:19:38 +00:00
|
|
|
@app.before_server_start
|
|
|
|
def setup(app, loop):
|
2017-08-29 21:05:57 +01:00
|
|
|
loop.set_task_factory(context.task_factory)
|
2021-03-10 09:19:38 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
app.run(port=9999, debug=True)
|