我可以将stdout
的所有输出重定向到我使用标准logging
模块设置的记录器吗?
(我有os.system调用,其输出我也想看到或者是封闭的打印语句)
答案 0 :(得分:4)
您可以使用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