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

问题描述 投票:0回答:1

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

fmt = ('%(asctime)s - %(name)s - %(levelname)s - '
       '%(filename)s:%(lineno)s - %(funcName)20s() - %(message)s')
formatter = logging.Formatter(fmt)
python logging flask
1个回答
1
投票

好的,我设法通过添加自定义过滤器来实现

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')
© www.soinside.com 2019 - 2024. All rights reserved.