将所有的标准输出/标准错误重定向到日志记录器

2个回答

1
虽然这不是完整的答案,但它可能会向您展示如何重定向以适应您的特定情况。这是我以前的做法。尽管我记不得为什么要这样做,或者我试图规避什么限制,但以下内容将stdoutstderr重定向到一个类中,用于print()语句。该类随后会写入屏幕和文件:
import os
import sys
import datetime

class DebugLogger():

    def __init__(self, filename):
        timestamp = datetime.datetime.strftime(datetime.datetime.utcnow(), 
                                               '%Y-%m-%d-%H-%M-%S-%f')
        #build up full path to filename
        logfile = os.path.join(os.path.dirname(sys.executable), 
                               filename + timestamp)
        self.terminal = sys.stdout
        self.log = open(logfile, 'a')

    def write(self, message):
        timestamp = datetime.datetime.strftime(datetime.datetime.utcnow(), 
                                               ' %Y-%m-%d-%H:%M:%S.%f')
        #write to screen
        self.terminal.write(message)
        #write to file
        self.log.write(timestamp + ' - ' + message)      
        self.flush()

    def flush(self):
        self.terminal.flush()
        self.log.flush()
        os.fsync(self.log.fileno())

    def close(self):
        self.log.close()


def main(debug = False):
    if debug:
        filename = 'blabla'
        sys.stdout = DebugLogger(filename)
        sys.stderr = sys.stdout
    print('test')

if __name__ == '__main__':
    main(debug = True)

1
import sys
import io

class MyStream(io.IOBase):
    def write(self, s):
        logger.error(s)

sys.stderr = MyStream()

print('This is an error', stream=sys.stderr)

这将使所有对 sys.stderr 的调用都传递给记录器。原始的调用仍然在 sys.__stderr__ 中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接