суббота, 6 декабря 2008 г.

Python syslog as it should be

First, the code:

from logging.handlers import SysLogHandler, SYSLOG_UDP_PORT
from logging import Handler
import socket

class UdpSysLogHandler(SysLogHandler):
def createLock(self): pass
def acquire(self): pass
def release(self): pass

def __init__(self, address=('127.0.0.1', SYSLOG_UDP_PORT), facility=SysLogHandler.LOG_USER):
Handler.__init__(self)
assert type(address) == tuple
self.address = address
self.facility = facility
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.formatter = None

def emit(self, record):
msg = self.format(record)
msg = self.log_format_string % (
self.encodePriority(self.facility,
self.mapPriority(record.levelname)),
msg)
try:
self.socket.sendto(msg, self.address)
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)

def close(self):
Handler.close(self)
self.socket.close()

How it is different from standard SysLogHandler in Python logging package?

First, a lock is eliminated. This lock is taken (in original version) for each logging operation. And IO is performed inside the lock, which is very bad.

def createLock(self): pass
def acquire(self): pass
def release(self): pass

Second, there is no support for logging through UNIX domain socket (/dev/log). This has slightly simplified the emit method.

One might say that UNIX domain sockets should be faster that actual networking UDP sockets, because they dont involve all the networking stack. In practice, however, I noticed that UNIX domain sockets perform much worser. I dont know why. If someone has a clue, please, let me know.

Комментариев нет: