将客户端IP信息添加到django记录器中 [英] Adding client IP info into django logger

查看:315
本文介绍了将客户端IP信息添加到django记录器中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将客户端IP添加到日志文件中,我已经考虑扩展Logger,但不知道如何访问请求对象并将IP放入记录对象中。



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
b b b b b b b b b b b b b b b b b b b b b b b b b b

代码来操作记录添加一个属性来让客户端IP
record.ip ='123.123.123.123'

super(RequestRotatingFileLogger, self).emit(record)


解决方案

一些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 =无
除了:
pass

super(RequestRotatingFileLogger,self).emit(record)

请求对象作为第二个参数例如。

  logger.info('message',request)


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)

这篇关于将客户端IP信息添加到django记录器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆