logging模块使⽤TCPUDP发送纯⽇志内容
logging模块使⽤TCP/UDP发送纯⽇志内容
python的logging模块允许使⽤多种⽅式(handler)记录/发送⽇志,包括:
logging
StreamHandler
FileHandler
logging.handlers
BufferingHandler
MemoryHandler
HTTPHandler
NTEventLogHandler
SMTPHandler
SocketHandler
DatagramHandler
SysLogHandler
常⽤的StreamHandler、FileHandler都好理解,将⽇志信息按照我们定义好的格式进⾏记录。但对于SocketHandler(TCP)和DatagramHandler(UDP),官⽅的解释为:
A handler class which writes logging records, in pickle format, to a streaming socket.
坑爹啊,我只是想发个⽇志⽽已,为什么要⾃作主张地把⽇志记录对象序列化后再以⼆进制形式发送?
查看SocketHandler源码,发现关键在makePickle()这个⽅法:
def makePickle(self, record):
"""
Pickles the record in binary format with a length prefix, and
returns it ready for transmission across the socket.
"""
ei = _info
if ei:
dummy = self.format(record) # just to get traceback text _text
<_info = None# to avoid Unpickleable error
import pickles = cPickle.dumps(record.__dict__, 1)
if ei:
<_info = ei  # for next handler
slen = struct.pack(">L", len(s))
return slen + s
该⽅法从⽇志记录⽣成pickle字符串,⽤于发送。解决的⽅法很简单,继承SocketHandler和DatagramHandler,重写该⽅法。只对其按指定的⽇志格式进⾏格式化,⽽不执⾏pickle的操作。代码如下:
from logging.handlers import *
class MySocketHandler(SocketHandler):
def makePickle(self, record):
return self.format(record)+'\n'
class MyDatagramHandler(DatagramHandler):
def makePickle(self, record):
return self.format(record)+'\n'
此后使⽤MySocketHandler和MyDatagramHandler发送的就是和FileHandler记录的⼀样的纯⽇志内容
了。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。