Spaces:
Running
Running
File size: 2,823 Bytes
99210cc |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
import logging
from logging.config import dictConfig
from contextvars import ContextVar
request_id: ContextVar[str] = ContextVar('request_id', default='')
request_session: ContextVar[dict] = ContextVar('request_session', default={})
# import logging
class RequestIDFilter(logging.Filter):
def filter(self, record: logging.LogRecord) -> bool:
record.request_id = request_id.get()
return True
log_config = {
"disable_existing_loggers": False,
'version': 1,
'formatters': {
'default': {
'format': '[%(asctime)s] %(levelname)s %(pathname)s %(module)s %(lineno)d -> %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S %z'
}},
'handlers': {'console': {
'class': 'logging.StreamHandler',
'formatter': 'default',
"stream": "ext://sys.stdout"
}},
"loggers": {
'root': {
'level': 'INFO',
'handlers': ['console']
}
}
}
log_config = {
"version": 1,
"disable_existing_loggers": False,
'filters': {
'request_id_filter': {
"()": RequestIDFilter
}
},
"formatters": {
'access': {
'()': 'uvicorn.logging.AccessFormatter',
'fmt': '[%(asctime)s] [%(request_id)s] %(levelprefix)s - %(client_addr)s - "%(request_line)s" %(status_code)s',
"datefmt": "%Y-%m-%d %H:%M:%S %z",
"use_colors": True
},
"default": {
"()": "uvicorn.logging.DefaultFormatter",
'fmt': '[%(asctime)s] [%(request_id)s] %(levelname)s %(pathname)s %(module)s %(lineno)d -> %(message)s',
# 'fmt': '[%(asctime)s] %(levelname)s %(pathname)s %(module)s %(lineno)d -> %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S %z',
"use_colors": True
},
},
"handlers": {
'access': {
'class': 'logging.StreamHandler',
'formatter': 'access',
'stream': 'ext://sys.stdout',
"filters": ['request_id_filter']
},
"default": {
"formatter": "default",
"class": "logging.StreamHandler",
"stream": "ext://sys.stdout",
"filters": ['request_id_filter']
},
},
"loggers": {
"log": {
"handlers": ["default"],
"level": "INFO",
"propagate": False
},
"uvicorn": {
"handlers": ["default"],
"level": "INFO",
"propagate": True
},
'uvicorn.access': {
'handlers': ['access'],
'level': 'INFO',
'propagate': False
},
'uvicorn.error': {
'level': 'INFO',
'propagate': False
}
},
}
dictConfig(log_config)
logger = logging.getLogger("log") |