作者:容易 2013-03-26 16:53:32
[root@hadoop-slave syslog]# cat mysyslog.py
from twisted.internet import reactor, stdio, defer
from twisted.internet.protocol import Protocol, Factory
from twisted.protocols.basic import LineReceiver
from twisted.enterprise import adbapi
import cx_Oracle
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):
# print 'Connection from %r' % self.transport
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
# print json.dumps(k)
log.msg('Connection from %s' % json.dumps(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
def startFactory(self):
# pool = cx_Oracle.SessionPool(user='xxxx',password='xxxxx',dsn='192.168.x.xx:1521/xxx',min=10,max=20,increment=2)
dbpool = adbapi.ConnectionPool('cx_Oracle', user='xxxxx', password ='xxxxx', dsn='192.168.x.xx:1521/xxxx',cp_min=10,cp_max=20,cp_reconnect=True,cp_running=True)
# def main():
# factory = SyslogdFactory()
# reactor.listenTCP(512, factory, 10)
# reactor.run()
# if __name__ == '__main__':
# main()
port = 514
iface = '0'
factory = SyslogdFactory()
top_service = service.MultiService()
#top_service 定义了一个子服务集
syslog_service = internet.TCPServer(port, factory, interface=iface)
#syslog_service 定义了一个子服务
syslog_service.setServiceParent(top_service)
#将syslog_service添加到top_service服务集
application = service.Application("mysyslog")
#定义根服务名mysyslog,其中application变量不能改
top_service.setServiceParent(application)
#将top_service添加到mysyslog服务
服务间的关系,如下
根服务(可包含多个子服务集,或子服务)
子服务集(可包含多个子服务)
通过twisted命名运行为daemon进程,该实例只是简单实用
twistd --logfile=/root/syslog/syslog.log --pidfile=/root/syslog/syslog.pid --python mysyslog.py
具体可以通过twisted --help查询相关运行参数
我的syslog服务计划,持续更新中
One Response