我正在尝试将客户端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)
答案 0 :(得分:8)
好的,在阅读了一些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)