要附加到列表的 Python 日志处理程序 [英] Python logging handler to append to list

查看:49
本文介绍了要附加到列表的 Python 日志处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有点类似于这个(未回答)的问题:

Somewhat similar to this (unanswered) question here:

https://stackoverflow.com/questions/33136398/python-logging-handler-that-appends-messages-to-list

我正在寻找使用处理程序来简单地将任何内容(通过过滤器)附加到python列表中.我会设想这样的代码:

I am looking to use a handler to simply append anything (passing a filter) to a python list. I would envisage some kind of code like this:

import logging
import sys
mylog = logging.getLogger()
mylog.setLevel(logging.DEBUG)

log_list = []
lh = logging.SomeHandler(log_list)
lh.setLevel(logging.DEBUG)

mylog.addHandler(lh)
mylog.warning('argh')
print log_list[0]

因此,问题是-我该如何实现呢?我可以使用什么 SomeHandler ?

The question is therefore - how can I implement this? What SomeHandler can I use?

推荐答案

这是一个幼稚的,非线程安全的实现:

Here is a naive, non thread-safe implementation:

import logging

class ListHandler(logging.Handler): # Inherit from logging.Handler
        def __init__(self, log_list):
                # run the regular Handler __init__
                logging.Handler.__init__(self)
                # Our custom argument
                self.log_list = log_list
        def emit(self, record):
                # record.message is the log message
                self.log_list.append(record.msg) 

这篇关于要附加到列表的 Python 日志处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆