Bidhan Roy
Bidhan Roy

Reputation: 431

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

I want to add request and user ids with logs of my Django project. Ways I found on internet need me to send extra request with every logger call like this,

logger.info('This is my info log line', extras={ 'request', request })

But I don't want to modify every existing logger call. Is it possible to this with handlers/formatters?

Upvotes: 3

Views: 4314

Answers (1)

hongshuning
hongshuning

Reputation: 77

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)

Upvotes: 2

Related Questions