Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding client IP info into django logger

Tags:

logging

django

ip

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)
like image 941
James Lin Avatar asked Aug 29 '12 23:08

James Lin


1 Answers

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)
like image 135
James Lin Avatar answered Nov 02 '22 09:11

James Lin