python - 在python中获取某个级别的所有日志?
问题描述
我有一个功能
import logging
def print_logs():
logging.info('info log 1.')
logging.warning('warning log 1.')
logging.error('error log 1.')
logging.error('error log 2.')
我想调用这个函数,然后获取指定日志级别的所有日志。所以我希望能够做类似的事情:
print_logs()
error_logs = get_logs_by_level('error')
或者
error_logs = get_logs_by_level(print_logs, 'error')
并且函数 print_logs 运行,并且error_logs
将是['error log 1.', 'error log 2']
这可能吗?
解决方案
以下是安装处理程序以捕获日志的示例。
这适用于 Python 2.7。对于 Python 3 替换cStringIO.StringIO
为io.StringIO
或io.BytesIO
。或者使用ListHander
也不需要的。
如果您希望在格式化之前保留日志记录或将每条消息的行分隔开。这可以调整,但需要编写Handler
.
import logging
import cStringIO
class Handler(object):
def __init__(self, handler):
self.handler = handler
def __enter__(self):
logging.root.handlers.append(self.handler)
return self.handler
def __exit__(self, type, value, tb):
logging.root.handlers.remove(self.handler)
def print_logs():
logging.info('info log 1.')
logging.warning('warning log 1.')
logging.error('error log 1.')
logging.error('error log 2.')
h = logging.StreamHandler(stream=cStringIO.StringIO())
h.setLevel('ERROR')
with Handler(h):
print_logs()
error_logs = h.stream.getvalue().splitlines()
error_logs
class RecordListHandler(logging.Handler):
def __init__(self):
logging.Handler.__init__(self)
self.log = []
def emit(self, record):
self.log.append(record)
class ListHandler(logging.Handler):
def __init__(self):
logging.Handler.__init__(self)
self.log = []
def emit(self, record):
msg = self.format(record)
self.log.append(msg)
h = RecordListHandler()
h.setLevel('ERROR')
with Handler(h):
print_logs()
error_logs = h.log
error_logs
h = ListHandler()
h.setLevel('ERROR')
with Handler(h):
print_logs()
error_logs = h.log
error_logs
推荐阅读
- javascript - GET 请求预检在浏览器中失败(使用 React 框架)
- python - 在带有 openpyxl 的 python 中使用 VLOOKUP 函数
- .net - Azure DevOps 在构建管道上从多个源还原包
- javascript - 将 webpack(环境)变量传递给 scss 文件
- javascript - 如何从一个js文件中获取axios/fetch的返回响应到函数中的另一个js文件
- github - NiFi 注册表-无法从 NiFi 1.9.2 中的 Git Hub 恢复流
- c# - 如果本地主机连接从浏览器关闭,HttpListener 会一直等待
- javascript - 开玩笑断言承诺递归
- python - unpickling 模型文件 python scikit-learn(管道(memory=None, steps=None, verbose=None))
- vue.js - 在 NuxtJs 中使用 fetch 上传文件和表单数据