Skip to main content
 首页 » 编程设计

python之在 flask 应用程序中将用户 ip 和用户 id 添加到日志文件

2025年01月19日10bjzhanghao

我正在使用标准的 Python 日志记录包在 Flask 应用程序中写入日志文件。我想添加用户 ip 地址,如果用户通过身份验证,我还想记录用户 ID。有人知道怎么做这个吗? 现在我的格式化程序看起来像这样

fmt = ('%(asctime)s - %(name)s - %(levelname)s - ' 
       '%(filename)s:%(lineno)s - %(funcName)20s() - %(message)s') 
formatter = logging.Formatter(fmt) 

请您参考如下方法:

好的,我经理通过添加一个 costum 过滤器来做到这一点

class ContextualFilter(logging.Filter): 
    def filter(self, log_record): 
        ''' Provide some extra variables to give our logs some better info ''' 
        log_record.utcnow = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S,%f %Z') 
        log_record.url = request.path 
        log_record.method = request.method 
        # Try to get the IP address of the user through reverse proxy 
        log_record.ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr) 
        if current_user.is_anonymous(): 
            log_record.user_id = 'guest' 
        else: 
            log_record.user_id = current_user.get_id() 
        return True 

可以添加到记录器中作为

std_logger.addFilter(ContextualFilter()) 

格式化程序应该是这样的

    fmt = ('%(utcnow)s - %(levelname)s - ' 
       'user_id:%(user_id)s - ip:%(ip)s - %(method)s - %(url)s - ' 
       '%(filename)s:%(lineno)s - %(funcName)20s() - %(message)s')