python输出重定向到窗口_将Python“print”输出重定向到Logg

还有一种方法是将记录器包装在一个对象中,该对象将对write的调用转换为记录器的log方法。import logging

import sys

class StreamToLogger(object):

"""

Fake file-like stream object that redirects writes to a logger instance.

"""

def __init__(self, logger, log_level=logging.INFO):

self.logger = logger

self.log_level = log_level

self.linebuf = ''

def write(self, buf):

for line in buf.rstrip().splitlines():

self.logger.log(self.log_level, line.rstrip())

logging.basicConfig(

level=logging.DEBUG,

format='%(asctime)s:%(levelname)s:%(name)s:%(message)s',

filename="out.log",

filemode='a'

)

stdout_logger = logging.getLogger('STDOUT')

sl = StreamToLogger(stdout_logger, logging.INFO)

sys.stdout = sl

stderr_logger = logging.getLogger('STDERR')

sl = StreamToLogger(stderr_logger, logging.ERROR)

sys.stderr = sl

这允许您轻松地将所有输出路由到您选择的记录器。如果需要,您可以在替换之前保存此线程中其他人提到的sys.stdout和/或sys.stderr,如果您以后需要恢复它。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值