作者:容易 2013-03-29 15:38:05
以下是syslog服务器的简单代码,基于tcp协议,该syslog服务基于twisted,通过twisted实现了日志异步入库的功能,以下只是简单的功能实现,以后逐步完善。
syslog 服务器代码
from twisted.internet import epollreactor
epollreactor.install()
from twisted.internet import reactor
from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.enterprise import adbapi
import time, re, math, json
from twisted.python import log
from twisted.application import internet, service
severity = ['emerg', 'alert', 'crit', 'err', 'warn', 'notice', 'info', 'debug', ]
facility = ['kern', 'user', 'mail', 'daemon', 'auth', 'syslog', 'lpr', 'news',
'uucp', 'cron', 'authpriv', 'ftp', 'ntp', 'audit', 'alert', 'at', 'local0',
'local1', 'local2', 'local3', 'local4', 'local5', 'local6', 'local7',]
fs_match = re.compile("<(.+)>(.*)", re.I)
class SyslogdProtocol(LineReceiver):
delimiter = '\n'
def connectionMade(self):
log.msg('Connection from %r' % self.transport)
def lineReceived(self, line):
k = {}
k['line'] = line.strip()
(fac, sev) = self._calc_lvl(k['line'])
k['host'] = self.transport.getHost().host
k['tstamp'] = time.time()
k['facility'] = fac
k['severity'] = sev
self.factory.dbpool.runOperation("insert into syslog values(:tstamp,:host,:facility,:severity,:line)",k)
def _calc_lvl(self, line):
lvl = fs_match.split(line)
if lvl and len(lvl) > 1:
i = int(lvl[1])
fac = int(math.floor(i / 8))
sev = i - (fac * 8)
return (facility[fac], severity[sev])
return (None, None)
class SyslogdFactory(Factory):
protocol = SyslogdProtocol
dbpool = adbapi.ConnectionPool('cx_Oracle', user='syslog', password ='oracle', dsn='192.168.xx.xx:1521/syslogdb',cp_min=10,cp_max=20,cp_reconnect=True)
port = 514
iface = '0'
factory = SyslogdFactory()
top_service = service.MultiService()
syslog_service = internet.TCPServer(port, factory, interface=iface)
syslog_service.setServiceParent(top_service)
application = service.Application("mysyslog")
top_service.setServiceParent(application)
One Response