如何同时将日志消息写入日志文件和控制台? [英] How do I write log messages to a log file and the console at the same time?

查看:71
本文介绍了如何同时将日志消息写入日志文件和控制台?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Does this code write to both a log file and the console at the same time?

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

推荐答案

否,它不会同时写入两者.print() 只会写入控制台.关于原始代码的简短说明.我想您在某处定义 message ,但是代码仍然不正确.您需要在 open 语句中的 a 周围加上引号,例如:

No, it will not write to both. print() will write to the console only. One quick note on your original code. I presume you define message somewhere, but the code is still incorrect. You need quotes around the a in the open statement, like this:

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

因为我假设您是要附加到文件中.否则,由于 a 不是已定义的变量,因此您的代码将引发 NameError .

since I presume you meant to append to the file. Otherwise, you code throws a NameError since a is not a defined variable.

但是,正如其他人所说,您应该强烈考虑使用记录模块.这是一个如何同时写入控制台和日志文件的简单示例.该代码部分来自此处此处:

However, as others have said, you should strongly consider using the logging module. Here is a simple example of how to write to both the console and a log file. The code is partially derived from here and here:

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对象.

Since logger objects can have more than one handler, we can create multiple handlers that write to different places. In my code, the function_logger function creates a logger object specific to the function in which it's called.

函数 f1() DEBUG 级及更高级别的消息记录到文件 f1.log 中,同时写入 ERROR 级别的消息以及更高版本的消息到控制台,每种消息的格式不同.

The function f1() logs DEBUG level messages and above to a file f1.log, while writing ERROR level messages and above to the console, with different formatting for each.

函数 f2(),但是什么也不记录到控制台,而只将 WARNING 级消息记录到其日志文件 f2.log .一次运行此脚本将在控制台上产生以下输出:

The function f2(), however, logs nothing to the console and only logs WARNING level messages to its log file f2.log. Running this script once yields this output on the console:

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

这篇关于如何同时将日志消息写入日志文件和控制台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆