Python使用basicConfig方法登录到控制台和fi

2024-06-11 18:03:53 发布

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

我不知道为什么这些代码会打印到屏幕上,而不是文件上?文件“example1.log”已创建,但未在其中写入任何内容。

#!/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')

我已经通过创建一个日志对象(example code)绕过了这个问题,但是它一直在困扰我为什么basicConfig()方法失败?

另外,如果我将basicConfig调用更改为:

logging.basicConfig(level=logging.DEBUG,
                    filename="example2.log",
                    format='%(asctime)s %(message)s',
                    handlers=[logging.StreamHandler()])

然后所有日志都在文件中,控制台中不显示任何内容


Tags: 文件todebuglogformat内容messagelogging
3条回答

对于控制台和文件都可以尝试这种良好的工作方式(在Python2.7中测试)

# set up logging to file
logging.basicConfig(
     filename='twitter_effect.log',
     level=logging.INFO, 
     format= '[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s',
     datefmt='%H:%M:%S'
 )

# set up logging to console
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)

logger = logging.getLogger(__name__)

在下面的示例中,可以根据日志目标的级别指定日志目标。例如,下面的代码允许INFO级别上的所有日志转到日志文件,而ERROR级别上的所有日志都转到控制台。

import logging
logging.root.handlers = []
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO , filename='ex.log')

# set up logging to console
console = logging.StreamHandler()
console.setLevel(logging.ERROR)
# set a format which is simpler for console use
formatter = logging.Formatter('%(asctime)s : %(levelname)s : %(message)s')
console.setFormatter(formatter)
logging.getLogger("").addHandler(console)

logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.exception('exp')

我不能在Python3.3上复制它。消息同时写入屏幕和'example2.log'。在Python<;3.3上,它创建文件,但它是空的。

代码:

from logging_tree import printout  # pip install logging_tree
printout()

显示FileHandler()未附加到Python<;3.3上的根记录器。

关于^{}的文档说handlers参数是在Python 3.3中添加的。Python 3.2文档中没有提到handlers参数。

相关问题 更多 >