添加客户端IP信息到Django的记录仪(Adding client IP info into dj

2019-07-31 06:41发布

我想在客户端IP地址添加到日志文件,我曾经想过延长记录器,但不知道如何访问请求对象,并把IP为记录对象

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)

Answer 1:

OK,阅读一些记录器的源代码后,我发现了一个哈克的方式做到这一点

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)

和记录时,通过该请求对象作为第二参数例如。

logger.info('message', request)


文章来源: Adding client IP info into django logger