-
使用 pssh 工具在 14 臺機器執行 grep 命令獲取包含某特徵的日誌
-
將 14 份日誌做爲標準輸入傳給 Python 腳本
-
Python 解析 stdin(標準輸入),將日期轉化爲 Python 中的日期格式,判斷以後將符合條件的特定內容取出並輸出到 stdout(標準輸出)
一. 使用 pssh 工具在 14 臺機器執行 grep 命令獲取包含某特徵的日誌
pip install pssh
pssh -l root -h RS_bj_14.txt -o result "grep some_tag /data/logs/api.log"複製代碼
-
-l 的意思是使用哪一個用戶執行
-
-h 是指定主機列表文件(換行隔開)
-
-o 是指定執行結果保存的文件夾
-
最後是須要執行的命令
紅色執行失敗的的那兩臺機器未包含符合咱們篩選條件的日誌
二. 將 14 份日誌做爲標準輸入傳給 Python 腳本
14 份日誌做爲標準輸入傳給 Python 腳本:
cat result/* | ./ab-result-format.py 15 15 00 10 > result_we_want.log複製代碼
import sys
import time
format = '%Y-%m-%dT%H:%M:%S+08:00'
h_start = int(sys.argv[1])
h_end = int(sys.argv[2])
m_start = int(sys.argv[3])
m_end = int(sys.argv[4])
stdin = sys.stdin.read().strip()
line_list = stdin.split('\n')
for item in line_list:
infos = item.split()
time_object = time.strptime(infos[0], format)
if h_start <= time_object.tm_hour <= h_end \
and m_start <= time_object.tm_min <= m_end:
print infos[8], infos[3], infos[4]複製代碼
爲了方便查看,日誌格式和日誌中的空格都用換行代替
$time_iso8601
$remote_addr
$host
$request_time
$upstream_response_time
$request
$status
$upstream_addr
$session_id;複製代碼
2017-12-19T00:03:57+08:00
2003:da8:2004:1000:***:ffd2:f0:9b1c
[2003:da8:2004:1000:****:ffaa:00f0:9b1c]
0.454
0.448
POST
/?Action=SubmitSyncTaskWithData
HTTP/1.1
200
[2003:da8:2004:1000:****:dd8b:00b7:38ae]:8080
f228d3941798f0d92c877a92a265f679複製代碼
-
接受 4 個參數,分別是起始的小時和分鐘,備用
-
讀取標準輸入 sys.stdin.read(),去掉頭尾無用的字符 strip(),循環處理每行日誌
-
拆分每行日誌 split()
-
將時間字符串轉爲時間對象,根據 4 個參數判斷小時和分鐘(這裏處理的比較粗糙,跨小時就沒辦法處理了,有興趣的讀者能夠作的更精細一點)
-
時間條件符合,打出須要的部分(這裏我須要的是 session_id, request_time, upstream_response_time 因此咱們print infos[8], infos[3], infos[4]注:Python 的 print 就是標準輸出
最後咱們使用 >將 Python 腳本的標準輸出重定向到 result_we_want.log 文件