0
作爲我的測試的一部分,試圖檢查套接字是否收到日誌。
所以一個線程發送日誌,主線程嘗試從套接字中檢索。如何通過套接字檢索python.logging日誌記錄
無法將接收到的數據轉換爲日誌記錄。
按照Python 2.7 docs試驗logging.makeLogRecord
。也試過pickle
/cPickle
import unittest
import socketLogger
import logging
import logging.handlers
#import cPickle as pickle
def test_StringReceivedIsSameAsStringSent():
host = 'localhost'
port = 9000
stringSent = "hello world!"
stringReceived = None
log_msg = None
def sendLogToSocket(host,port, stringSent):
logger = logging.getLogger('mylogger') # to log Led Observer output over a socket
sh = logging.handlers.SocketHandler(host,port) # handler to write to socket
logger.addHandler(sh)
logger.critical(stringSent)
logger.removeHandler(sh)
sh.close()
import threading
t = threading.Thread(target=sendLogToSocket, args=(host,port,stringSent)) # socket requires 2 different ports if on the same machine
t.start() # send log in a thread
import socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #INET => IPv4, STREAM => TCP
serversocket.bind((host,port)) # 'localhost' => implies only visible within the same machine
serversocket.listen(1) # accept 1 connection only
(clientsocket, address) = serversocket.accept()
stringReceived = clientsocket.recv(1024)
print 'socketlistener: string received: ', repr(stringReceived)
#obj = pickle.loads(stringReceived)
#print 'un pickling log: ', obj
#log_msg = logging.makeLogRecord(obj)
log_msg = logging.makeLogRecord(stringReceived)
print 'socketlistener: converted to log: ', log_msg
clientsocket.close()
serversocket.close()
t.join() # wait for the log thread to finish
print 'string sent: ', repr(stringSent), ' received: ', repr(stringReceived
self.assertEqual(stringSent, stringReceived)
if __name__ == "__main__":
test_StringReceivedIsSameAsStringSent()
輸出
E:\> python testSocket.py
socketlistener: string received: '\x00\x00\x01}}q\x01(U\x0frelativeCreatedq\x02 [email protected]\x18\x00\x0b\x00\x00\x00\x00U\x07processq\x03M\xb0IU\x04argsq\x04NU\x06moduleq \x05U\ntestSocketq\x06U\x08funcNameq\x07U\x0fsendLogToSocketq\x08U\x08exc_textq\ tNU\x04nameq\nU\x08myloggerq\x0bU\x06threadq\x0cM|"U\x07createdq\rGA\xd6a\x040\x b1x\xd5U\nthreadNameq\x0eU\x08Thread-1q\x0fU\x05msecsq\[email protected]\x88(\x00\x01\x00\x0 0\x00U\x08filenameq\x11U\rtestSocket.pyq\x12U\x07levelnoq\x13K2U\x0bprocessNameq \x14U\x0bMainProcessq\x15U\x08pathnameq\x16h\x12U\x06linenoq\x17K\x12U\x03msgq\x 18U\x0chello world!q\x19U\x08exc_infoq\x1aNU\tlevelnameq\x1bU\x08CRITICALq\x1cu.
'
Traceback (most recent call last):
File "testSocket.py", line 47, in <module>
test_StringReceivedIsSameAsStringSent()
File "testSocket.py", line 36, in test_StringReceivedIsSameAsStringSent
log_msg = logging.makeLogRecord(stringReceived)
File "C:\Users\myuser\AppData\Local\Continuum\Miniconda2\lib\logging\__init_ _.py", line 340, in makeLogRecord
rv.__dict__.update(dict)
ValueError: dictionary update sequence element #0 has length 1; 2 is required
請使用'print repr(string_variable)'而不是'print' –
@ArindamRoychowdhury在這裏你去。 – vijiboy