0

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

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

2 回答 2

26

不,它不会写入两者。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函数创建了一个特定于调用它的函数的记录器对象。

该函数将级别消息和更高级别的消息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
于 2012-07-20T14:12:08.140 回答
0

不,它只写入文件。你应该使用logging模块。请参阅http://docs.python.org/library/logging.html

于 2012-07-20T07:02:21.013 回答