python脚本通过监控docker容器日志监控hyperledger fabric区块高度、共识时延信息
查看节点的具体容器ID
docker inspect --format="{{.Id}}" container_name
// 以peer0 为例
docker inspect --format="{{.Id}}" peer0.org1.example.com
找到该容器日志所在文件位置(一般在/var/lib/docker/containers下)
编写python监控脚本
#!/usr/bin/python
# encoding=utf-8
# Filename: monitorLog.py
# www.jbxue.com
import MySQLdb
import os
import re
import signal
import subprocess
import time
//脚本写入mysql数据库
db = MySQLdb.connect("127.0.0.1","root","123456","数据库名",charset = 'utf8')
cursor = db.cursor()
//.log 文件名
logFile1 = "ad649153d0d3cc924418e7e6e242699c0c0e9e5b8ae619a20e92b96ae-json.log"
def monitorLog(logFile):
print '监控的日志文件 是%s' % logFile
popen = subprocess.Popen('tail -f ' + logFile +'| grep --line-buffer "CommitWithPvtData"', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
pid = popen.pid
print('Popen.pid:' + str(pid))
while True:
line =popen.stdout.readline()
# 判断内容是否为空
if line:
relist = []
redict = {}
strs = str(line)
pattern = 'block [[0-9]+]'
ret = re.search(pattern, strs)
//区块高度
number = filter(str.isdigit, ret.group())
pattern = '[0-9]+-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+.[0-9]+'
ret = re.search(pattern, strs)
//出块时间
data = ret.group()
pattern2 = '(state_validation=[0-9]+ms block_commit=[0-9]+ms state_commit=[0-9]+ms)'
ret = re.search(pattern2, strs)
blocktime= re.findall(r'\d+', ret.group())
//state_validation时间
redict["state_validation"] = int(blocktime[0])
//block_commit时间
redict["block_commit"] = int(blocktime[1])
//state_commit时间
redict["state_commit"] = int(blocktime[2])
//总时间
redict["total"] = int(blocktime[0]) + int(blocktime[1]) + int(blocktime[2])
sql = "INSERT INTO log(data,total,pattern) VALUES (\'%s\', \'%s\',\'%s\')" % (
str(data), str(number), blocktime[0] + " " + blocktime[1] + " " + blocktime[2])
cursor.execute(sql)
db.commit()
if __name__ == '__main__':
monitorLog(logFile1)
nohup python log.py &
或者 python log.py &
ps -aux | grep "log.py"