如何将python中Logger对象的输出发送到文件?

2024-04-19 16:40:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python中的日志记录库。我正在使用几个记录器对象来输出信息。我已经到了输出太多的地步,我需要将其发送到日志文件而不是控制台。 我找不到一个函数来配置logger对象的输出流,basicConf函数似乎没有起到作用。 这就是我所拥有的:

import logging # Debug logging framework
logging.basicConfig(filename='loggggggmeee.txt')
logger = logging.getLogger('simulation')
logger.setLevel(logging.INFO)

#--------------- etc-------------------#

logger.info('This is sent to the console')

有什么想法吗?谢谢!在


Tags: 文件对象函数debugimport信息logging记录
1条回答
网友
1楼 · 发布于 2024-04-19 16:40:09

尝试添加这样的文件位置它将解决您的问题:

import logging # Debug logging framework
logging.basicConfig(filename='c:\\loggggggmeee.txt')
logger = logging.getLogger('simulation')
logger.setLevel(logging.INFO)

#       - etc         -#

logger.info('This is sent to the console')

顺便说一下,没有特定位置的文件将在模块库中。。。

我真的建议你阅读Logging HOWTO它非常简单和有用。

而且Cookbook有很多有用的例子。

关于从文档中命名伐木工人的另一个好建议:

a good convention to use when naming loggers is to use a module-level logger, in each module which uses logging, named as follows:

logger = logging.getLogger(__name__)

This means that logger names track the package/module hierarchy, and it’s intuitively obvious where events are logged just from the logger name.

相关问题 更多 >