Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Tree: ffa9b945c3
Fetching contributors…

Cannot retrieve contributors at this time

59 lines (51 sloc) 1.845 kB
#!/usr/bin/env python
"""
ListeningSocketHandler
======================
A python logging handler.
logging.handlers.SocketHandler is a TCP Socket client that sends log records to a tcp server.
This class is the opposite.
When a TCP client connects (e.g. telnet or netcat), log records are streamed through the connection.
"""
import logging
import sys
try:
from gevent import socket, Greenlet
except ImportError:
import socket
import threading
class ListeningSocketHandler(logging.Handler):
def __init__(self, port=0, ipv6=False):
super(ListeningSocketHandler, self).__init__()
self.port = port
self.ipv6 = ipv6
self.clients = set()
if self.ipv6:
self.socket = socket.socket(socket.AF_INET6)
self.socket.bind(("::", self.port))
else:
self.socket = socket.socket(socket.AF_INET)
self.socket.bind(("0.0.0.0", self.port))
self.socket.listen(5)
def start_accepting(self):
while True:
conn, addr = self.socket.accept()
self.clients.add(conn)
try:
self._accept_thread = Greenlet(start_accepting, self)
except NameError:
self._accept_thread = threading.Thread(target=start_accepting, args=(self,))
self._accept_thread.start()
def emit(self, record):
closed_clients = set()
for client in self.clients:
try:
client.sendall(record.getMessage())
client.sendall("\n")
except socket.error:
closed_clients.add(client)
for client in closed_clients:
client.close() # just to be sure
self.clients.remove(client)
def getsockname(self):
return self.socket.getsockname()
Jump to Line
Something went wrong with that request. Please try again.