3

From REST request I will get an id which needs to be added to all log statements.

I know one way will be to add the string to every log statement as below

logging.info('{} References invoked {}'.format(_id, refs))

But, wanted to know if there is any easy way where I can bake the _id to every log statement.

1 Answer 1

1

With a help of good friend in Real python, I was able to solve the problem.

import sys
import logging


def get_id_logger():
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s - '
                                  '%(levelname)-8s - '
                                  '[%(filename)s:%(lineno)d] - '
                                  '{_id} - '
                                  '%(message)s '.
                                  format(_id=locals().get('_id', '')))
    handler = logging.StreamHandler(sys.stdout)
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return logger


def set_logger_id(logger, _id):
    logger_format = '%(asctime)s - ' \
                     '%(levelname)-8s - ' \
                     '[%(filename)s:%(lineno)d] - ' \
                     '{_id} - ' \
                    '%(message)s '.\
                    format(_id=locals().get('_id', ''))
    new_formatter = logging.Formatter(logger_format)
    handlers = logger.handlers
    for h in handlers:
        h.setFormatter(new_formatter)

test_script.py:

from logger import get_id_logger, set_logger_id

logger = get_id_logger()
logger.debug('Lets test something without req_id')


req_id = 9870
set_logger_id(logger, req_id)

logger.info('Lets test something with req_id')
logger.info('Lets test something with req_id again')
logger.info('Lets test something with req_id again')

req_id = 3456
set_logger_id(logger, req_id)
logger.info('Lets test something with req_id again')
logger.debug('Lets test something with req_id again')
Sign up to request clarification or add additional context in comments.

1 Comment

While this works, you're not using python logging to it's fullest. See this (old but relevant) blog post on better way to do this. blog.mcpolemic.com/2016/01/18/adding-request-ids-to-flask.html

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.