单独记录Flask请求:如何按ID删除Python日志处理程序



所以我有以下问题:

我使用的是Flask,我想生成两种不同类型的日志文件:一种是常规日志文件,它将所有内容记录到一个文件中;另一种是Logger/Handler,它只记录传入请求和相应的传出响应,每个请求都有一个单独的文件。在实践中,我使用了一个具有自定义级别和易于调用函数的自定义日志类。但我试着将其分解为基本内容:

app = Flask(__name__)
general_logger = logging.getLogger(__name__)
# add_handlers_to_general_logger()
@app.before_request
def log_incoming_request():
request_id = get_current_request_id()
unique_logger = logging.getLogger("{0}.{1}".format(__name__, request_id))
# add_handler_to_unique_logger()
unique_logger.info("INCOMING REQUEST")

@app.route('/')
def index():
general_logger.info("Index called!")
file_A.do_something_A()  # this function takes X seconds to process, general_logger is also used in there
return "Hello World"

@app.after_request
def log_outgoing_response(response):
request_id = get_current_request_id()  # same id as in before_request
unique_logger = logging.getLogger("{0}.{1}".format(__name__, request_id))
unique_logger.info("OUTGOING RESPONSE")
return response

现在的问题是,尽管它有效,但我认为创建这么多不同的记录器不是一个好主意。index((中调用的函数需要未知的秒数来处理,具体取决于发送的请求数据,并且应该能够同时处理多个请求。我的想法是删除@app.after_request.中的相应处理程序

因此,问题是:在@app.before_request中添加特定处理程序后,如何在@app.after_request中按名称正确删除正确的处理程序,如:

@app.before_request
def log_incoming_request():
request_id = get_current_request_id()
unique_logger = logging.getLogger("unique")
add_handler_to_unique_logger(request_id)
unique_logger.info("INCOMING REQUEST")
@app.after_request
def log_outgoing_response(response):
request_id = get_current_request_id()  # same id as in before_request
unique_logger = logging.getLogger("{0}.{1}".format(__name__, request_id))
unique_logger.info("OUTGOING RESPONSE")
unique_logger.removeHandler(request_id)
return response

或者有没有其他方法可以正确地记录单独的请求日志文件(文件名中有request_id(?

谢谢!

在内存管理成为问题之前,我不会担心它。在任何情况下,您都可以删除日志模块持有的引用:

del logging.root.manager.loggerDict[unique_logger_id]

记录器对象本身当然只有在代码中对它的所有其他引用都消失的情况下才会停止存在。如果您也在使用唯一的处理程序,我还建议对它们调用close(),以便清理使用过的文件资源。

最新更新