5

我正在尝试将客户端 IP 添加到日志文件中,我曾考虑扩展 Logger,但不确定如何访问请求对象并将 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)
4

1 回答 1

10

好的,在阅读了一些 Logger 源代码后,我发现了一种 hacky 方法

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)
于 2012-08-30T00:35:06.267 回答