我能否将所有来自
stdout
的输出重定向到一个使用标准 logging
模块设置的记录器中?
(我有一些 os.system 调用的输出也想看到,或者偶尔会有 print 语句)您可以尝试使用以下总结自此篇文章的建议:
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