2012-07-20 102 views
-3

此代码是否同时写入日志文件和控制台?如何将日志消息同时写入日志文件和控制台?

logFile = open("logfile.log",a) 
print >>logFile,message 
logFile.close() 
+12

当你尝试它时它做了什么...... – avasal 2012-07-20 06:53:34

+1

它可能使用多个处理程序。一个用于处理文件('logging.FileHandler('mylog.log')'),另一个用于处理控制台('logging.StreamHandler()')。请参阅https://docs.python.org/2/howto/logging-cookbook.html – 2014-07-27 06:20:15

回答

16

不,它不会写入两者。 print()只会写入控制台。关于您的原始代码的一个简短说明。我认为你在某个地方定义了message,但代码仍然不正确。因为我相信你的意思是要附加到文件

open("logfile.log", "a") 

:您需要a各地报价在open声明,像这样。否则,由于a不是定义的变量,因此您的代码会抛出NameError

然而,正如其他人所说,你应该强烈考虑使用logging模块。以下是如何写入控制台和日志文件的简单示例。该代码是部分地herehere得出:

import inspect 
import logging 

def function_logger(file_level, console_level = None): 
    function_name = inspect.stack()[1][3] 
    logger = logging.getLogger(function_name) 
    logger.setLevel(logging.DEBUG) #By default, logs all messages 

    if console_level != None: 
     ch = logging.StreamHandler() #StreamHandler logs to console 
     ch.setLevel(console_level) 
     ch_format = logging.Formatter('%(asctime)s - %(message)s') 
     ch.setFormatter(ch_format) 
     logger.addHandler(ch) 

    fh = logging.FileHandler("{0}.log".format(function_name)) 
    fh.setLevel(file_level) 
    fh_format = logging.Formatter('%(asctime)s - %(lineno)d - %(levelname)-8s - %(message)s') 
    fh.setFormatter(fh_format) 
    logger.addHandler(fh) 

    return logger 

def f1(): 
    f1_logger = function_logger(logging.DEBUG, logging.ERROR) 
    f1_logger.debug('debug message') 
    f1_logger.info('info message') 
    f1_logger.warn('warn message') 
    f1_logger.error('error message') 
    f1_logger.critical('critical message') 

def f2(): 
    f2_logger = function_logger(logging.WARNING) 
    f2_logger.debug('debug message') 
    f2_logger.info('info message') 
    f2_logger.warn('warn message') 
    f2_logger.error('error message') 
    f2_logger.critical('critical message') 

def main(): 
    f1() 
    f2() 
    logging.shutdown() 

main() 

由于记录对象可以有多个处理程序,我们可以创建写入不同的地方多个处理程序。在我的代码中,function_logger函数为它所调用的函数创建一个特定的记录器对象。

功能f1()日志DEBUG级消息和以上到文件f1.log,一边写ERROR级消息和以上到控制台,用不同的格式为每个。

但是,函数f2()不向控制台记录任何内容,只将WARNING级消息记录到其日志文件f2.log。分别

2012-07-20 10:46:38,950 - f1 - error message 
2012-07-20 10:46:38,953 - f1 - critical message 

这个输出f1.logf2.log,:运行此脚本一次债收益率此输出在控制台上

f1.log

2012-07-20 10:46:38,950 - 26 - DEBUG - debug message 
2012-07-20 10:46:38,950 - 27 - INFO  - info message 
2012-07-20 10:46:38,950 - 28 - WARNING - warn message 
2012-07-20 10:46:38,950 - 29 - ERROR - error message 
2012-07-20 10:46:38,953 - 30 - CRITICAL - critical message 

f2.log

2012-07-20 10:46:38,960 - 36 - WARNING - warn message 
2012-07-20 10:46:38,960 - 37 - ERROR - error message 
2012-07-20 10:46:38,960 - 38 - CRITICAL - critical message 
+0

的第一个示例一个细节:从Py27开始,“logger.setLevel(logging.DEBUG)#默认情况下,记录所有消息”是必不可少的。没有它,setLevel()调用处理程序将不起作用:详细信息级别将被锁定在logging.warning上。 – kakyo 2013-09-08 01:56:12