[Django]-How to add request id in Django logs without modifying logger call?

2👍

If request is a constant in one logger, you can use custom Filter to archive this goal:

import logging
class CustomFilter(logging.Filter):
    def __init__(self, request):
        self.request = request
    def filter(self, record):
        record.request = self.request
        return True

Then add %(request)s into your formatter, and add CustomFilter to your logger’s filters:

logger.addFilter(CustomFilter(CONSTANT_REQUEST))
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter('%(request)s %(levelname)s %(message)s'))
logger.addHandler(handler)

Leave a comment