python 将信息级别记录到文件

python logging info level to a file

我开始使用日志记录来跟踪我的代码中发生的事情并从这里开始:

https://realpython.com/python-logging/

根据那篇文章,此代码应创建并向名为 moses_data_extraction.log

的日志文件添加一行
import logging
import os

logging.basicConfig(filename='moses_data_extraction.log',
                    filemode='w',
                    format='%(asctime)s - %(message)s',
                    datefmt='%d-%b-%y %H:%M:%S',
                   level=logging.INFO)
logging.info('This will get logged to a file')
print(os.path.isfile('moses_data_extraction.log'))

最后一行给出了 FALSE

但是没有创建文件。实际上什么也没有发生,没有文件没有错误。

知道我哪里做错了吗?

如果最后的打印语句给你 True,则文件必须在你当前的工作目录中创建。

要检查文件所在的目录,您可以使用以下命令检查当前工作目录:

import os
print(os.getcwd())

或者,您可以在代码中指定完整的文件路径名,以将日志文件放置在您想要的位置。