4000-520-616
欢迎来到免疫在线!(蚂蚁淘生物旗下平台)  请登录 |  免费注册 |  询价篮
主营:原厂直采,平行进口,授权代理(蚂蚁淘为您服务)
咨询热线电话
4000-520-616
当前位置: 首页 > 新闻动态 >
新闻详情
将Python“print”输出重定向到Logg - 问答 - Python中文网
来自 : www.cnpython.com/qa/35... 发布时间:2021-03-24
将Python“print”输出重定向到Logg - 问答 - Python中文网 Python中文网 - 问答频道, 解决您学习工作中的Python难题和Bug Python常见问题登录 新用户注册 \"Python中文网\"首 页问题库教程文章问答专家标签库课程中心 将Python“print”输出重定向到Logg

2021-03-24 12:45:06 发布

您现在位置:Python中文网/ 问答频道 /正文15143 3\"用户头像\"

网友

男|程序猿一只,喜欢编程写python代码。

我有一个Python脚本,它使用“Print”来打印到stdout。我最近通过Python Logger添加了日志记录,如果启用了日志记录,那么这些打印语句将转到Logger。我不想修改或删除这些打印报表。

我可以通过“log.info(“some info msg”)来登录。我想做这样的事情:

if logging_enabled: sys.stdout=log.infoprint(\"test\")

如果启用了日志记录,那么“test”应该像记录log.info(“test”)一样记录。如果没有启用日志记录,“test”应该只打印到屏幕上。

这可能吗?我知道我可以用类似的方式将stdout指向文件(请参见:redirect prints to log file)

3条回答网友1楼 ·

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

Ferry Boender就是这么做的,provided under the GPL license在a post在his website:

import loggingimport sysclass 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 = slstderr_logger = logging.getLogger(\'STDERR\')sl = StreamToLogger(stderr_logger, logging.ERROR)sys.stderr = sl

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

网友2楼 ·

你有两个选择:

打开日志文件并用它替换sys.stdout,而不是函数:

log = open(\"myprog.log\", \"a\")sys.stdout = log print(\"Hello\") # nothing is printed because it goes to the log file instead.

将print替换为日志函数:

# If you\'re using python 2.x, uncomment the next line#from __future__ import print_functionprint = log.info print(\"Hello!\") # nothing is printed because log.info is called instead of print
网友3楼 ·

当然,您既可以打印到标准输出,也可以附加到日志文件,如下所示:

# Uncomment the line below for python 2.x#from __future__ import print_functionimport logginglogging.basicConfig(level=logging.INFO, format=\'%(message)s\')logger = logging.getLogger()logger.addHandler(logging.FileHandler(\'test.log\', \'a\'))print = logger.infoprint(\'yo!\')
相关问题

本文链接: http://fakeprint.immuno-online.com/view-696781.html

发布于 : 2021-03-24 阅读(0)
公司介绍
联络我们
服务热线:4000-520-616
(限工作日9:00-18:00)
QQ :1570468124
手机:18915418616
官网:http://