importloggingimportlogging.handlersrootLogger=logging.getLogger('')rootLogger.setLevel(logging.DEBUG)socketHandler=logging.handlers.SocketHandler('localhost',logging.handlers.DEFAULT_TCP_LOGGING_PORT)# don't bother with a formatter, since a socket handler sends the event as# an unformatted picklerootLogger.addHandler(socketHandler)# Now, we can log to the root logger, or any other logger. First the root...logging.info('Jackdaws love my big sphinx of quartz.')# Now, define a couple of other loggers which might represent areas in your# application:logger1=logging.getLogger('myapp.area1')logger2=logging.getLogger('myapp.area2')logger1.debug('Quick zephyrs blow, vexing daft Jim.')logger1.info('How quickly daft jumping zebras vex.')logger2.warning('Jail zesty vixen who grabbed pay from quack.')logger2.error('The five boxing wizards jump quickly.')
importloggingimportlogging.handlersimportpickleimportsocketserverimportstructclassLogRecordStreamHandler(socketserver.StreamRequestHandler):"""Handler for a streaming logging request.
This basically logs the record using whatever logging policy is
configured locally.
"""defhandle(self):"""
Handle multiple requests - each expected to be a 4-byte length,
followed by the LogRecord in pickle format. Logs the record
according to whatever policy is configured locally.
"""whileTrue:chunk=self.connection.recv(4)iflen(chunk)<4:breakslen=struct.unpack('>L',chunk)[0]chunk=self.connection.recv(slen)whilelen(chunk)<slen:chunk=chunk+self.connection.recv(slen-len(chunk))obj=self.unPickle(chunk)record=logging.makeLogRecord(obj)self.handleLogRecord(record)defunPickle(self,data):returnpickle.loads(data)defhandleLogRecord(self,record):# if a name is specified, we use the named logger rather than the one# implied by the record.ifself.server.lognameisnotNone:name=self.server.lognameelse:name=record.namelogger=logging.getLogger(name)# N.B. EVERY record gets logged. This is because Logger.handle# is normally called AFTER logger-level filtering. If you want# to do filtering, do it at the client end to save wasting# cycles and network bandwidth!logger.handle(record)classLogRecordSocketReceiver(socketserver.ThreadingTCPServer):"""
Simple TCP socket-based logging receiver suitable for testing.
"""allow_reuse_address=Truedef__init__(self,host='localhost',port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,handler=LogRecordStreamHandler):socketserver.ThreadingTCPServer.__init__(self,(host,port),handler)self.abort=0self.timeout=1self.logname=Nonedefserve_until_stopped(self):importselectabort=0whilenotabort:rd,wr,ex=select.select([self.socket.fileno()],[],[],self.timeout)ifrd:self.handle_request()abort=self.abortdefmain():logging.basicConfig(format='%(relativeCreated)5d%(name)-15s%(levelname)-8s%(message)s')tcpserver=LogRecordSocketReceiver()print('About to start TCP server...')tcpserver.serve_until_stopped()if__name__=='__main__':main()