Adding client IP info into django logger

2020-07-13 18:33发布

问题:

I am trying to add the client IPs to the log files, I have thought about extending the Logger, but not sure how to access the request object and put IP into the record object

from logging.handlers import RotatingFileHandler

class RequestRotatingFileLogger(RotatingFileHandler, object):
    def emit(self, record):
        """
        code to manipulate the record to add an attribute to have client IP
        record.ip = '123.123.123.123'
        """
        super(RequestRotatingFileLogger,self).emit(record)

回答1:

OK, after reading some Logger source code, I found out a hacky way to do it

from logging.handlers import RotatingFileHandler

class RequestRotatingFileLogger(RotatingFileHandler, object):
        def emit(self, record):
            record.ip = '0.0.0.0'
            try:
                request = record.args[0]
                record.ip = request.META.get('REMOTE_ADDR')  
                record.args = None
            except:
                pass

            super(RequestRotatingFileLogger,self).emit(record)

and when logging, pass the request object as second parameter eg.

logger.info('message', request)