Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用流重定向python日志消息_Python_Logging_Stream_Handler_Stringio - Fatal编程技术网

使用流重定向python日志消息

使用流重定向python日志消息,python,logging,stream,handler,stringio,Python,Logging,Stream,Handler,Stringio,我想将日志消息重定向到某种处理方法(例如,为了保存队列中的所有消息)。目前,我正在尝试使用logging.StreamHandler来写入StringIO,然后在其他地方读取它。在我的例子中,这可能是一个线程不断地从流中读取数据,但也可能是对每个日志条目调用的回调方法 import threading import time import sys import logging from StringIO import StringIO # this thread shall read from

我想将日志消息重定向到某种处理方法(例如,为了保存队列中的所有消息)。目前,我正在尝试使用logging.StreamHandler来写入StringIO,然后在其他地方读取它。在我的例子中,这可能是一个线程不断地从流中读取数据,但也可能是对每个日志条目调用的回调方法

import threading
import time
import sys
import logging
from StringIO import StringIO

# this thread shall read from a stream 
# continuously and 
def tread_fn( stream ):
    while not stream.eof():       <=== this is not valid but my current approach
        l = stream.readline()
        do_something( l )

stream = StringIO()

handler = logging.StreamHandler(stream)
log = logging.getLogger()
log.setLevel( logging.INFO )

# replace all log handlers
for handler in log.handlers: 
    log.removeHandler(handler)
log.addHandler(handler)

thread = threading.Thread(target = tread_fn, args=[stream])
thread.start()

for i in range(3):        
    time.sleep(1)
    log.error("test")          <=== should be handled line by line
导入线程
导入时间
导入系统
导入日志记录
从StringIO导入StringIO
#该线程应从流中读取
#不断地
def胎面_fn(流):

而不是stream.eof():您一次问了两个问题-它们应该是单独的问题。您的主要目标可以通过使用
QueueHandler
来实现,该处理器在Python 3.2及更高版本中可用,但在项目的早期Python版本中也可用。

一个选项是编写自己的处理程序,将其传入的日志记录放到队列中。然后后台线程一次读取一条记录(注意,不需要序列化)。不过,这取决于你下一步想做什么。