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

我不知道为什么这个代码打印到屏幕上,而不是文件? 文件“example1.log”被创build,但没有写在那里。

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

我通过创build一个日志logging对象( 示例代码 )“绕过”了这个问题,但是却让我不知道为什么basicConfig()方法失败了?

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

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

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

我不能在Python 3.3上重现它。 消息被写入屏幕和'example2.log' 。 在Python <3.3它创build文件,但它是空的。

代码:

 from logging_tree import printout # pip install logging_tree printout() 

显示FileHandler()未附加到Python <3.3的根logging器。

logging.basicConfig()的文档说, handlers参数是在Python 3.3中添加的。 Python 3.2文档中没有提到handlers参数。

试试这个工作正常(在Python 2.7中testing)为控制台和文件

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