我试图读取位于/var/log/mongodb
其内容的MongoDB日志文件,如下所示:
2019-11-04T05:04:00.390-0800我命令[conn38649]命令loldb。$ cmd命令:update {更新:“ SUBSCRIPTION”,命令:true,writeConcern:{w:1},$ db:“ loldb”} numYields:0 reslen:295锁:{全局:{acquisitionCount:{r:460,w:460}},数据库:{acquisitionCount:{w:460}},集合:{acquisitionCount:{w:459}},oplog :{acquisitionCount:{w:1}}}协议:op_query 568ms
2019-11-04T05:04:00.396-0800我命令[conn38657]命令loldb.SUBSCRIPTION命令:find {查找:“ SUBSCRIPTION”,过滤器:{客户ID:75824180,PoliceDepartmentID:1},投影:{},$ readPreference: {mode:“ secondaryPreferred”},$ db:“ loldb”} planSummary:COLLSCAN keysExamined:0 docsExamined:69998 cursorExhausted:1 numYields:550 nreturned:1 reslen:430锁:{全局:{AcquisitionCount:{r:1102}}} ,数据库:{quirenCount:{r:551}},集合:{accountCount:{r:551}}}协议:op_query 424ms
2019-11-04T05:04:00.402-0800我命令[conn38735]命令loldb.SUBSCRIPTION命令:查找{查找:“ SUBSCRIPTION”,过滤器:{客户ID:75824164},投影:{},$ readPreference:{模式:“ secondaryPreferred“},$ db:” loldb“} planSummary:COLLSCAN keysExamined:0 docsExamined:58142 cursorExhausted:1 numYields:456 nreturned:1 reslen:417锁:{全局:{acquisitionCount:{r:914}},数据库:{ acquisitionCount:{r:457}},Collection:{AccountCount:{r:457}}}协议:op_query 374ms
每个块引用都是单行条目
文件的内容每秒更新一次,我需要读取文件,如果查询时间protocol:op_query 385ms
超过300ms,则需要将整个日志/行保存到另一个文本文件中slow_queries.text
。
我正在从中读取的.log
文件是文件,但是内容看起来像JSON格式(如果我写错了,请纠正我),再加上时间戳和命令类型,是否有任何有效的方式来读取这种格式的数据?我只是逐行阅读单词。
另外,我该怎么做,以便在.log
不每次运行脚本的情况下自动读取对文件所做的更改?
我只是在本地计算机上尝试过此操作,可能需要为您的用例做一些工作。但是我添加了一些评论,所以也许这会对您有所帮助:
编辑:我添加了一个时间戳检查,您将必须根据需要对其进行配置
#!/bin/bash
# continously read from the file and pipe it into the while loop
tail -F "test.log" | \
while read LINE
do
# get timestamp from LINE and get time in seconds
timeinseconds="$(grep -P "^\S*" | date -d - +%s)"
# get current timestamp before 5 minutes
timebeforefivemin="$(date -d '-5 minutes' +%s)"
# only log if timestamp of line is smaller to time before 5 min
if [[ $(expr $timeinseconds - $timebeforefivemin) -lt 0 ]];
then
# get the time of the query from the line
querytime="$(echo "$LINE" | grep -oP '\d+ms' | grep -oP '\d+')"
#if the grep was successful and the query time is greater than 300
if [ $? = 0 ] && [ "$querytime" -gt 300 ]
then
# echo the line into the slow_queries file -> change it to the path you want
echo "$LINE" >> slow_queries.txt
fi
fi
done
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句