使用Python日志套接字处理程序接收到奇怪字符
我在用Python(2.7)写程序,需要把信息记录到一个远程服务器上。我使用了logging.handlers这个库,但发送的信息有点奇怪。目前我在用Python文档网站上提供的SocketServer代码。
import logging
import logging.handlers
class TestMan():
def __init__(self,xmlString):
formatter = logging.Formatter('%(levelname)s : %(name)s - %(asctime)s - %(message)s')
logging.basicConfig(filename='test.log',level=logging.DEBUG,format='%(levelname)s : %(name)s - %(asctime)s - %(message)s')
log = logging.getLogger(__name__)
socket = logging.handlers.SocketHandler('localhost',1030)
socket.setLevel(logging.INFO)
socket.setFormatter(formatter)
log.addHandler(socket)
log.info("Starting Test")
收到的内容如下(不能直接粘贴文本,所以我截图了)
https://i.stack.imgur.com/Z3nZD.png
服务器代码:
import SocketServer
class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print "{} wrote:".format(self.client_address[0])
print self.data
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 1030
# Create the server, binding to localhost on port 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
1 个回答
0
SocketHandlers发送的数据在发送之前会被“打包”。
https://docs.python.org/2/library/logging.handlers.html#logging.handlers.SocketHandler
emit()这个函数会把记录的属性字典打包,然后以二进制格式写入到socket中。如果socket出现错误,它会默默地丢弃这个数据包。如果之前的连接断开了,它会重新建立连接。在接收端,要把打包的数据解包成LogRecord,可以使用makeLogRecord()这个函数。