如何将日志消息同时写入日志文件和控制台?

时间:2012-07-20 06:52:40

标签: python logging

此代码是否同时写入日志文件和控制台?

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

2 个答案:

答案 0 :(得分:23)

不,它不会同时写入。 print()将仅写入控制台。关于原始代码的快速说明。我假设您在某处定义message,但代码仍然不正确。您需要a语句中open周围的引号,如下所示:

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

因为我认为你打算附加到该文件。否则,您的代码会抛出NameError,因为a不是已定义的变量。

但是,正如其他人所说,你应该强烈考虑使用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()

由于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

此输出分别位于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

答案 1 :(得分:0)

没有。它只写入文件。您应该使用logging模块。见http://docs.python.org/library/logging.html

相关问题