【问题标题】:adding user ip and user id to logfile in flask application在烧瓶应用程序中将用户 ip 和用户 id 添加到日志文件
【发布时间】:2018-07-20 21:40:06
【问题描述】:

我正在使用标准 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】:

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

    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')
    

    【讨论】:

    猜你喜欢
    • 2015-06-10
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 2021-01-14
    • 2015-08-12
    • 2019-06-01
    • 2011-10-12
    相关资源
    最近更新 更多