5
我可以将所有输出从stdout
重定向到我已使用标准logging
模块设置的记录器吗? (我有使用os.system调用,其输出我也希望看到或occational打印语句)将stdout重定向到Python中的记录器
我可以将所有输出从stdout
重定向到我已使用标准logging
模块设置的记录器吗? (我有使用os.system调用,其输出我也希望看到或occational打印语句)将stdout重定向到Python中的记录器
你也许可以利用在this post建议的,总结如下:
import logging
class LoggerWriter:
def __init__(self, logger, level):
self.logger = logger
self.level = level
def write(self, message):
if message != '\n':
self.logger.log(self.level, message)
def main():
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("demo")
info_fp = LoggerWriter(logger, logging.INFO)
debug_fp = LoggerWriter(logger, logging.DEBUG)
print >> info_fp, "An INFO message"
print >> debug_fp, "A DEBUG message"
if __name__ == "__main__":
main()
当运行该脚本打印:
INFO:demo:An INFO message
DEBUG:demo:An DEBUG message
重复http://stackoverflow.com/questions/975248/redirecting-sys-stdout-to-python-logging的 – synthesizerpatel 2012-02-23 10:10:37
谢谢!不知何故,自动建议只显示标准输出重定向到文件... – Gerenuk 2012-02-23 10:20:04