1

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?

MANOJ
  • 716
  • 4
  • 10
  • 29

1 Answers1

0

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}
Kevin S
  • 930
  • 10
  • 19
  • for each API request content of extra data is going to chanage. – MANOJ Dec 21 '18 at 06:05
  • If its constantly changing then you'll have to supply the extra argument, no way around that. If it is static or mostly static then you can use the solution I've provided – Kevin S Dec 21 '18 at 13:55