Python 使用 basicConfig 方法登录到控制台和文件 [英] Python using basicConfig method to log to console and file

查看:32
本文介绍了Python 使用 basicConfig 方法登录到控制台和文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么这段代码会打印到屏幕上,而不是打印到文件中?文件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')

我已经绕过"了通过创建日志对象来解决这个问题,但它一直困扰着我为什么 basicConfig() 方法失败?

I have "bypassed" this problem by creating a logging object, but it keeps bugging me why basicConfig() approach failed?

附注.如果我将 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.

logging.basicConfig()handlers 参数是在 Python 3.3 中添加的.handlers 参数未在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆