简体   繁体   English

动态更改 uvicorn 中的日志级别

[英]Dynamically change logs level in uvicorn

I have a Fastapi API running with uvicorn.我有一个运行 uvicorn 的 Fastapi API。 I use uvicorn logging like so:我像这样使用 uvicorn 日志记录:

if __name__ == "__main__":
    uvicorn.run("main:app", host=host, port=int(port), reload=True, log_level=log_level,
                log_config="config/logging.yaml")

What I would like to achive is beeing able to change the log_level through an endpoint.我想要实现的是能够通过端点更改 log_level。 Something like:就像是:

@app.put("/api/log/{level}")
def change_log_level(level):
    #something that changes the log level.

I tried to make a global variable log_level but it didn't work and I'm not sure how to change it as the log_level is in the uvicorn.run instruction.我试图创建一个全局变量log_level但它不起作用,我不确定如何更改它,因为 log_level 在uvicorn.run指令中。 It is as well in the config.yaml file, so I'm not really sure were to change it...它也在 config.yaml 文件中,所以我不确定是否要更改它...
I'm open to try the logging with another library if needed如果需要,我愿意尝试使用另一个库进行日志记录

You could try something like this:你可以尝试这样的事情:

@app.put("/api/log/{level}")
def change_log_level(level):
    logging_level = your_function_to_map_url_level_to_logging_level(level)
    logging.getLogger('uvicorn').setLevel(logging_level)

You might want to do this for logger 'uvicorn' as above, or perhaps 'uvicorn.access' or 'uvicorn.error' , or any combination of these.您可能想为上面的记录器'uvicorn'执行此操作,或者可能是'uvicorn.access''uvicorn.error' ,或这些的任何组合。

There's a uvicorn.config.LOG_LEVELS dictionary mapping strings like 'critical' to logging.CRITICAL , etc. You might want to use that in your_function_to_map_url_level_to_logging_level , but you'd need to handle invalid levels passed in via the URL.有一个uvicorn.config.LOG_LEVELS字典将字符串(如'critical'映射到logging.CRITICAL等。您可能希望在your_function_to_map_url_level_to_logging_level中使用它,但您需要处理通过 URL 传入的无效级别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM