首页 > 解决方案 > 在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']

这可能吗?

标签: pythonpython-logging

解决方案


以下是安装处理程序以捕获日志的示例。

这适用于 Python 2.7。对于 Python 3 替换cStringIO.StringIOio.StringIOio.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

推荐阅读