它可以像登录到
StringIO对象一样简单:
import loggingtry: from cStringIO import StringIO # Python 2except importError: from io import StringIOlog_stream = StringIO() logging.basicConfig(stream=log_stream, level=logging.INFO)logging.info('hello world')logging.warning('be careful!')logging.debug("you won't see this")logging.error('you will see this')logging.critical('critical is logged too!')print(log_stream.getvalue())
输出量
INFO:root:hello world警告:root:请小心!错误:根:您将看到此也记录了CRITICAL:root:critical!
如果您只想记录WARN,INFO和ERROR级别的消息,则可以使用过滤器进行记录。
LevelFilter下面检查每个日志记录的级别号,仅允许所需级别的那些记录:
import loggingtry: from cStringIO import StringIO # Python 2except importError: from io import StringIOclass LevelFilter(logging.Filter): def __init__(self, levels): self.levels = levels def filter(self, record): return record.levelno in self.levelslog_stream = StringIO() logging.basicConfig(stream=log_stream, level=logging.NOTSET)logging.getLogger().addFilter(LevelFilter((logging.INFO, logging.WARNING, logging.ERROR)))logging.info('hello world')logging.warning('be careful!')logging.debug("you won't see this")logging.error('you will see this')logging.critical('critical is no longer logged!')print(log_stream.getvalue())
输出量
INFO:root:hello world警告:root:请小心!错误:根:您将看到此
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)