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

Jov*_*vik 48 python console logging screen file

我不知道为什么这段代码打印到屏幕上,而不是文件?创建了文件"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')
Run Code Online (Sandbox Code Playgroud)

我通过创建一个日志记录对象(示例代码)来"绕过"这个问题,但它一直困扰我为什么basicConfig()方法失败?

PS.如果我将basicConfig调用更改为:

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

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

kar*_*eek 36

尝试这个工作正常(在python 2.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__)
Run Code Online (Sandbox Code Playgroud)


jfs*_*jfs 22

我无法在Python 3.3上重现它.消息被写入屏幕和'example2.log'.在Python <3.3上,它创建了文件,但它是空的.

代码:

from logging_tree import printout  # pip install logging_tree
printout()
Run Code Online (Sandbox Code Playgroud)

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

文档logging.basicConfig()说这个handlers参数是在Python 3.3中添加的.handlersPython 3.2文档中未提及该参数.

  • @ wjimenez5271:这不完全正确.如果您查看修复[@Jovik打开的问题](http://bugs.python.org/issue16521)的初始修补程序,那么您会看到[如果Python 3.2上的未知关键字参数,例如`handlers`,它会引发ValueError给出了](http://hg.python.org/cpython/rev/d7660ccd8470).[当前代码](http://hg.python.org/cpython/file/11a920a26f13/Lib/logging/__init__.py#l1707)也可能引发ValueError(尽管出于其他原因). (3认同)
  • @Jovik:尽管我目前还没有看到它,但可能存在一些逻辑.您可以尝试在http://bugs.python.org上报告 (2认同)

jxr*_*mos 21

使用该方法的另一种技术basicConfig是在语句中设置所有处理程序并在事后检索它们,如......

import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(module)s %(funcName)s %(message)s',
                    handlers=[logging.FileHandler("my_log.log", mode='w'),
                              logging.StreamHandler()])
stream_handler = [h for h in logging.root.handlers if isinstance(h , logging.StreamHandler)][0]
stream_handler.setLevel(logging.INFO)
Run Code Online (Sandbox Code Playgroud)

更明智的做法是在外部构建流处理程序实例,并将它们配置为独立的对象,然后将其传递给处理程序列表,如下所示...

import logging

stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(module)s %(funcName)s %(message)s',
                    handlers=[logging.FileHandler("my_log.log", mode='w'),
                              stream_handler])
Run Code Online (Sandbox Code Playgroud)


Wes*_* Na 6

在下面的示例中,您可以根据其级别指定日志目标.例如,下面的代码允许通过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')
Run Code Online (Sandbox Code Playgroud)