我正在尝试将每个请求的请求号附加到日志中:
借助python日志记录模块,我可以使用以下命令将ID附加到每个日志中:
id = uuid();
logger = logging.loggerAdapter(logging.getlogger('root'), {"RequestNumber" : id});
logger.info('this is a log message')
使用Bunyan记录
import bunyan
import logging
import sys
logger = logging.getLogger()
#logger = logging.loggerAdapter(logging.getlogger('root'), {"RequestNumber" : id});
config = {
'formatters': {
'bunyan': {
'()' : 'bunyan.BunyanFormatter'
}
},
'handlers': {
'debug': {
'class': 'logging.StreamHandler',
'formatter': 'bunyan',
'stream': 'ext://sys.stdout'
},
},
'root': {
'level': 'DEBUG',
'handlers': ['debug']
},
'version': 1
}
import logging.config
logging.config.dictConfig(config)
logger.debug("This is a log message")
logger.debug("This is a log message")
logger.debug("This is a log message")
但是在Bunyan文档中,找到附加字典的唯一方法如下:
logger.debug("This is a log message with extra context", extra = {'some': 'additional data'})
问题是必须在每个日志命令中附加RequestNumber。
我可以将loggerAdapter与bunyan一起使用吗?
答案 0 :(得分:0)
如果extra的内容大部分或全部保持静态,则可以使用functools中的partial。例如,
>>> from functools import partial
>>> logger.debug = partial(logger.debug, extra={"some_data":"right here"})
>>> logger.debug("test")
{"name": "root", "msg": "test", "some_data": "right here", "time": "2018-12-20T23:50:00Z", "hostname": "DESKTOP-DAQKYZ", "level": 20, "pid": 6840, "v": 0}
>>> logger.debug("danger, danger!")
{"name": "root", "msg": "danger, danger!", "some_data": "right here", "time": "2018-12-20T23:51:41Z", "hostname": "DESKTOP-DAQKYZ", "level": 20, "pid": 6840, "v": 0}