首页 > 解决方案 > 在控制台中运行时防止 Flask 双重记录

问题描述

我正在使用 Python Flask 和 Connexion 创建一个 REST API。很难弄清楚使用这两个库如何进行日志记录,并且在尝试在本地运行/调试时遇到了双重日志记录的奇怪问题。

app/log.py

import logging
from flask import g, has_request_context
import uuid

def request_id():
    if 'request_id' not in g:
        g.request_id = uuid.uuid4()

    return g.request_id

class AppFilter(logging.Filter):
    def filter(self, record):
        record.request_id = request_id() if has_request_context() else 'app'
        return True

formatter = logging.Formatter('%(asctime)s %(request_id)s %(module)s:%(levelname)s %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
handler.addFilter(AppFilter())

main.py

import connexion
from config import config
import json
import logging
from app.log import handler

# initiate swagger/connexion
application = connexion.App(__name__, specification_dir='./')
application.add_api('swagger.yml')

# logging
application.app.logger.handlers.pop() 
application.app.logger.addHandler(handler)
application.app.logger.setLevel(logging.DEBUG)
application.app.logger.debug('application starting...')

# if we're running in standalone mode, run the application
if __name__ == '__main__':
    application.run(host='0.0.0.0', port=5000)

上面的代码让我使用自定义日志格式,每个请求在请求期间都获得一个 UUID。虽然这可行,但我无法弄清楚如何停止双重记录。正如您所见,main.py我弹出(唯一)处理程序并添加我自己的处理程序,当我将处理程序打印到控制台时,只有一个 - 我添加的那个。

这可行,但在一定数量的消息之后,它才开始双重记录:

2019-10-17 10:00:22,737 09031bdb-5105-4b73-9e7d-a609f42a471e inbound:application starting...
2019-10-17 10:00:22,747 09031bdb-5105-4b73-9e7d-a609f42a471e inbound:INFO inbound
2019-10-17 10:00:22,755 09031bdb-5105-4b73-9e7d-a609f42a471e config:DEBUG Cache miss: 90002
2019-10-17 10:00:22,755 09031bdb-5105-4b73-9e7d-a609f42a471e firewall:DEBUG Connecting to x
2019-10-17 10:00:22,861 09031bdb-5105-4b73-9e7d-a609f42a471e firewall:DEBUG Get x for "90002"
2019-10-17 10:00:23,062 09031bdb-5105-4b73-9e7d-a609f42a471e firewall:DEBUG interfaces: source=v1 dest=v2
DEBUG:flask.app:interfaces: source=v1 dest=v2
2019-10-17 10:00:23,062 09031bdb-5105-4b73-9e7d-a609f42a471e firewall:DEBUG Found matching policy: 980cf552-5aaf-51e9-6c39-6480d51af2ad
DEBUG:flask.app:Found matching policy: 980cf552-5aaf-51e9-6c39-6480d51af2ad
2019-10-17 10:00:23,062 09031bdb-5105-4b73-9e7d-a609f42a471e firewall:DEBUG Found matching policy: eff53daa-b4f6-51e9-b79f-25b26b9f8537
DEBUG:flask.app:Found matching policy: eff53daa-b4f6-51e9-b79f-25b26b9f8537

好像处理程序已被重新添加。我不确定是否正在重新添加处理程序,或者我是否以错误的方式进行处理。

这是我在整个应用程序中记录的方式,例如:

inbound.py

from flask import request, current_app

def index():
    current_app.logger.info('inbound')
    # do stuff....

标签: pythonloggingflaskconnexion

解决方案


利用

application.app.logger.handlers.clear()

代替

application.app.logger.handlers.pop()

推荐阅读