使Python记录器记录所有stdout和stderr消息 [英] Making Python loggers log all stdout and stderr messages

查看:210
本文介绍了使Python记录器记录所有stdout和stderr消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用python日志记录软件包,并编写一个Log类,我想将stdout和stderr放入日志文件中:

Using the python logging package, and writing a class Log, I'd like to tee stdout and stderr to a log file :

log = Log("log.txt")
print "line1"
print "line2"
print >>sys.stderr, "err1"
del log
print "line to screen only"

输出日志文件将包含:

16/11/2017 09:51:58 INFO - line1
16/11/2017 09:51:58 INFO - line2
16/11/2017 09:51:58 INFO - err1

有什么想法可以编写此Log类,同时保留"logging"包的优点(时间戳等)吗?

Any idea how to write this Log class, keeping the advantages of the "logging" package (time-stamps, ...) ?

推荐答案

实现您要求的正确的方法是使用Logger对象.它为您提供了更多的灵活性.这个对象可以绑定到多个处理程序;您需要一个流处理程序来将消息记录到 sys.stdout 上,并且需要一个文件处理程序来将其记录到一个文件中.然后,您既可以打印到屏幕上,又可以通过一个命令登录到文件.

The right way to achieve what you ask is to use Logger object. It gives you much more flexability. This object can be bound to multiple handlers; You need a streamhandler to log message to sys.stdout and a file handler to log it to a file. You then both print to the screen and log to a file in a single command.

import logging

# create logger 
logger = logging.getLogger('example')
logger.setLevel(logging.INFO)

# create file handler which logs messages
fh = logging.FileHandler('fh.log')
fh.setLevel(logging.DEBUG)

# create console handler to print to screen
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)

# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)

# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)

现在,每次对 logger.info(msg)的调用都将被打印到屏幕上,并写入到 fh.log 文件中.

Now every call to logger.info(msg) will be printed both to the screen, and written to fh.log file.

还有另一种方法,您可以替换 sys.stdoutsys.stderr 流对象.创建一个类并对其进行自定义(此处是原始答案):

There is another way, where you can replace sys.stdout and sys.stderr stream objects. Create a class and customize it (original answer here):

import sys

class writer(object):
    _fh = None
    _orig_stdout = sys.stdout

   def __init__(self):
       _fh = open('logging.log', 'w')

    def write(self, data):
        fp.write(data)
        _orig_stdout.write(data)

    def flush():
        _orig_stdout.flush()

logger = writer()

sys.stdout = logger
sys.stderr = logger

这篇关于使Python记录器记录所有stdout和stderr消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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