使用python获取交换机syslog日志并使用jQuery在html上展示
个人博客地址
需求
现网有部分pop点独立于海外,无法发送日志给内网日志服务器,同时最近网内有比较重要割接,所以临时写一个脚本来展示网内日志
思路
使用socket接收syslog数据,udp 514,数据部分格式化后写入js文档,html调用js文档来实现日志可视化
效果
python代码
import socket,re,os def syslog(date): date = date.replace('\"','\'') pri = re.findall('\d+',date)[0] pri = int(pri) level = re.findall('<\d+>',date)[0] div_class = 'debug' if pri%8 == 0: date = date.replace(level,'emerg ') div_class = 'error' elif pri%8 == 1: date = date.replace(level,'alert ') div_class = 'error' elif pri%8 == 2: date = date.replace(level,'crit ') div_class = 'error' elif pri%8 == 3: date = date.replace(level,'error ') div_class = 'error' elif pri%8 == 4: date = date.replace(level,'warning ') div_class = 'warning' elif pri%8 == 5: date = date.replace(level,'notice ') elif pri%8 == 6: date = date.replace(level,'info ') elif pri%8 == 7: date = date.replace(level,'debug ') return date,div_class s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) address = ('172.16.0.33',514) s.bind(address) while True: date,address = s.recvfrom(10240) date = date.decode(encoding='utf8') date,div_class = syslog(date) print(date) with open ('/var/www/html/log.js','a') as f: f.write(''' \n$('#log').prepend("<div class = '%s'>%s</div>")'''%(div_class,date.rstrip()))
前端 代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf8"> <meta http-equiv="Refresh" content="60" > <title>syslog</title> <script src="jquery-3.6.0.slim.min.js"></script> <style> *{margin:0; padding: 0;} .debug{background-color: rgb(175, 175, 248);} .warning{background-color:yellow;} .error{background-color: red;} </style> </head> <body> <div id="log"> </div> <script src="log.js"> </script> </body> </html>
以驱魔为理想,为生计而奔波