简体   繁体   English

如何在 Python 中将另一个库的控制台日志消息重定向到文件

[英]How to redirect another library's console logging messages to a file, in Python

The fastAPI library that I import for an API I have written, writes many logging.INFO level messages to the console, which I would like either to redirect to a file-based log, or ideally, to both console and file.我为已编写的 API 导入的fastAPI库将许多 logging.INFO 级别的消息写入控制台,我希望将其重定向到基于文件的日志,或者理想情况下重定向到控制台和文件。 Here is an example of fastAPI module logging events in my console:这是我的控制台中 fastAPI 模块记录事件的示例:

在此处输入图片说明

So I've tried to implement this Stack Overflow answer ("Easy-peasy with Python 3.3 and above"), but the log file it creates ("api_screen.log") is always empty....所以我试图实现这个Stack Overflow 答案(“Easy-peasy with Python 3.3 and above”),但它创建的日志文件(“api_screen.log”)总是空的......

# -------------------------- logging ----------------------------
logging_file = "api_screen.log"

logging_level = logging.INFO
logging_format = '  %(message)s'
logging_handlers = [logging.FileHandler(logging_file), logging.StreamHandler()]

logging.basicConfig(level = logging_level, format = logging_format, handlers = logging_handlers)
logging.info("------logging test------")

Even though my own "------logging test------" message does appear on console within the other fastAPI logs:即使我自己的“------logging test------”消息确实出现在其他 fastAPI 日志的控制台上:

在此处输入图片说明

As you can see here it's created the file, but it has size zero.正如你在这里看到的,它创建了文件,但它的大小为零。

在此处输入图片说明

So what do I need to do also to get the file logging working?那么我还需要做什么才能使文件记录工作?

There are multiple issues here.这里有多个问题。 First and most importantly: basicConfig does nothing if a logger is already configured, which fastAPI does.首先,也是最重要的是: basicConfig做什么,如果一个记录器已经配置,这fastAPI一样。 So the handlers you are creating are never used.所以你正在创建的处理程序永远不会被使用。 When you call logging.info() you are sending a log to the root logger which is printed because the fastAPI has added a handler to it.当您调用logging.info()您将向根记录器发送一个日志,该日志被打印出来,因为 fastAPI 已向其添加了一个处理程序。 You are also not setting the level on your handlers.您也没有在处理程序上设置级别。 Try this code instead of what you currently have:试试这个代码,而不是你目前拥有的:

logging_file = "api_screen.log"
logging_level = logging.INFO

logging_fh = logging.FileHandler(logging_file)
logging_sh = logging.StreamHandler()
logging_fh.setLevel(logging_level)
logging_sh.setLevel(logging_level)

root_logger = logging.getLogger()
root_logger.addHandler(logging_fh)
root_logger.addHandler(logging_sh)

logging.info('--test--')

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

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