Python使用basicConfig方法登录到控制台和文件 [英] Python using basicConfig method to log to console and file
问题描述
我不知道为什么这个代码打印到屏幕,但不是文件?创建文件example1.log,但没有写入。
I don't know why this code prints to the screen, but not to the file? File "example1.log" is created, but nothing is written there.
#!/usr/bin/env python3
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(message)s',
handlers=[logging.FileHandler("example1.log"),
logging.StreamHandler()])
logging.debug('This message should go to the log file and to the console')
logging.info('So should this')
logging.warning('And this, too')
我通过创建一个日志对象a href =https://www.synthetos.com/logging-in-python-programs/>示例代码),但它一直告诉我为什么basicConfig()方法失败?
I have "bypassed" this problem by creating a logging object (example code), but it keeps bugging me why basicConfig() approach failed?
PS。如果我改变basicConfig调用:
PS. If I change basicConfig call to:
logging.basicConfig(level=logging.DEBUG,
filename="example2.log",
format='%(asctime)s %(message)s',
handlers=[logging.StreamHandler()])
然后所有日志都在文件中,控制台中不显示任何内容
Then all logs are in the file and nothing is displayed in the console
推荐答案
我无法在Python 3.3上重现它。消息被写入屏幕和'example2.log'
。在Python< 3.3它创建文件,但它是空的。
I can't reproduce it on Python 3.3. The messages are written both to the screen and the 'example2.log'
. On Python <3.3 it creates the file but it is empty.
代码:
from logging_tree import printout # pip install logging_tree
printout()
显示 FileHandler()
未附加到Python< 3.3的根记录器。
shows that FileHandler()
is not attached to the root logger on Python <3.3.
a href =http://docs.python.org/dev/library/logging.html#logging.basicConfig> logging.basicConfig()
说在Python 3.3中添加句柄
参数。 处理程序
参数在Python 3.2文档中未提及。
The docs for logging.basicConfig()
say that handlers
argument is added in Python 3.3. The handlers
argument isn't mentioned in Python 3.2 documentation.
这篇关于Python使用basicConfig方法登录到控制台和文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!