此代码是否同时写入日志文件和控制台?
logFile = open("logfile.log",a)
print >>logFile,message
logFile.close()
Run Code Online (Sandbox Code Playgroud)
Ric*_*ano 24
不,它不会写入两者.print()将仅写入控制台.关于原始代码的快速说明.我假设您定义了message某个地方,但代码仍然不正确.您需要a在open语句中使用引号,如下所示:
open("logfile.log", "a")
Run Code Online (Sandbox Code Playgroud)
因为我认为你打算附加到文件.否则,您抛出一个代码,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()
Run Code Online (Sandbox Code Playgroud)
由于logger对象可以有多个处理程序,因此我们可以创建多个处理程序来写入不同的位置.在我的代码中,该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
Run Code Online (Sandbox Code Playgroud)
该输出在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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)