将用户ip和用户id添加到flask应用程序中的logfile

时间:2018-02-10 04:46:48

标签: python logging flask

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

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

1 个答案:

答案 0 :(得分:1)

好的我经理通过添加costum过滤器

来做到这一点
<div class="container-fluid" id="intro">

可以作为

添加到记录器中
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())