ElasticSearch默認輸出INFO級別的日志到日志文件中,但是一次成功的http請求是TRACE級別,要想記錄所有的HTTP請求需要在elasticsearch.yml文件中添加logger.org.elasticsearch.http: TRACE配置。
日志文件中的記錄形式如圖所示:


每條記錄有時間戳,日志級別,是否為http。如果為http請求,則還有請求的http方法。
QPS統計
思路:篩選出所有HTTP請求,然后以秒為時間單位統計出每一秒的請求次數。
file_name="docker-cluster_server.json" #日志文件
#篩選出http的記錄,然后把http響應過濾掉,只留下請求
grep HttpTracer ${file_name} | grep -E 'GET|POST|PUT|DELETE|HEAD|CONNECT|OPTIONS' > temp_file2.log
#截取出時間部分的文本
awk -F ',' '{print $2}' temp_file2.log | awk -F '"' '{print $4}' > temp_file3.log
#排序並統計每一秒的請求
sort temp_file3.log | uniq -c > result.log
#輸出結果
cat result.log | while read line
do
echo $line
done
#刪除中間的臨時文件
rm temp_file2.log temp_file3.log result.log

QPS實時監控
思路:獲取當前時間(秒級時間),去日志文件查該時間下的HTTP請求數量,用while循環不斷刷新結果。
file_name="../logs/docker-cluster_server.json" #日志文件
while :
do
clear
current_time=`date "+%Y-%m-%dT%H:%M:%S"` #當前時間
sleep 1
grep ${current_time} ${file_name} > temp_file1.log #獲取當前時間下的日志記錄
grep HttpTracer temp_file1.log | grep -E 'GET|POST|PUT|DELETE|HEAD|CONNECT|OPTIONS' > temp_file2.log #過濾出HTTP請求,http響應不需要
awk -F ',' '{print $2}' temp_file2.log | awk -F '"' '{print $4}' > temp_file3.log #截取出時間部分的文本
qps=`wc -l < temp_file3.log`
# 輸出
printf "%-30s %-20s\n" "Current Time" "QPS"
printf "%-30s %-20s\n" ${current_time} ${qps}
# 通過輸入參數自定義刷新時間間隔
if [ -n "$1" ]; then
sleep $1
else
sleep 1
fi
rm temp_file1.log temp_file2.log temp_file3.log
done

待解決: 避免使用臨時文件來記錄中間結果
參考文獻:
ElasticSearch日志配置:https://www.cnblogs.com/cocowool/p/elasticsearch-log-config.html
elasticsearch docker 開啟日志:https://blog.csdn.net/weixin_42209307/article/details/114261820
