如何将日志消息同时写入日志文件和控制台?
此代码是否同时写入日志文件和控制台?
logFile = open("logfile.log",a)
print >>logFile,message
logFile.close()
-
不,它不会同时写入两者。
print()
只会写入控制台。关于原始代码的简短说明。我想您在message
某处定义,但是代码仍然不正确。您需要a
在open
语句中使用引号,例如:open("logfile.log", "a")
因为我认为您是要附加到文件中。否则,您的代码将抛出一个
NameError
因为a
未定义的变量。但是,正如其他人所说,您应该强烈考虑使用日志记录模块。这是一个如何同时写入控制台和日志文件的简单示例。该代码部分源自此处和此处:
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
函数创建一个特定于其调用函数的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.log
和中f2.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