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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With