尝试将变量中的日志(打印到控制台并使用记录器存储到文件)存储在变量中,以便将其流式传输到Web服务。
Python 3.4.7
from contextlib import redirect_stdout
import sys, io, logging
def log_config(logfile, mode):
FileFormatter = logging.Formatter(
"%(asctime)s [%(funcName)-12.12s] [%(levelname)-8.8s] %(message)s")
ConsoleFormatter = logging.Formatter("[%(asctime)s] : %(message)s")
logger = logging.getLogger()
logger.setLevel(logging.INFO)
consoleHandler = logging.StreamHandler(sys.stdout)
consoleHandler.setFormatter(ConsoleFormatter)
fileHandler = logging.FileHandler(logfile, mode='w')
fileHandler.setFormatter(FileFormatter)
if mode == 'console':
logger.addHandler(consoleHandler)
elif mode == 'file':
logger.addHandler(fileHandler)
elif mode == 'both':
logger.addHandler(fileHandler)
logger.addHandler(consoleHandler)
return logger
step_comment_io = io.StringIO()
logger = log_config('test.log', 'both')
with redirect_stdout(step_comment_io):
print ('printing')
# would like the below line also to be in stdout
logger.info('logging')
step_comment_io.getvalue()
预期输出:
“正在打印\记录\ n”
实际输出:
“正在打印\ n”