I am trying to append the request number to the log for each request:
With python logging module I was able to use the below command to append the id to each logs:
id = uuid();
logger = logging.loggerAdapter(logging.getlogger('root'), {"RequestNumber" : id});
logger.info('this is a log message')
With Bunyan logging
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")
But in bunyan documentation only way found to append the extra dictionary is as below:
logger.debug("This is a log message with extra context", extra = {'some': 'additional data'})
problem with this is that RequestNumber has to be appended in each log command.
Is there any way that I can use loggerAdapter with bunyan?
If the content of extra is mostly or entirely going to remain static you could use partial from functools. For example,
>>> 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}