MySQL 慢查詢日誌為多行結構,單條記錄包含:
# User@Host: user[user] @ [10.4.10.12] Id: 69641319
# Query_time: 0.000148 Lock_time: 0.000023 Rows_sent: 0 Rows_examined: 202
SET timestamp=1456717595;
select `Id`, `Url` from `File` where `Id` in ('201319', '201300');
# Time: 160229 11:46:37
需將多行合併為一事件,再用 Grok 解析結構化欄位。
filebeat:
prospectors:
- paths:
- /www.ttlsa.com/logs/mysql/slow.log
document_type: mysqlslowlog
input_type: log
multiline:
negate: true
match: after
pattern: '^# User@Host:'
registry_file: /var/lib/filebeat/registry
output:
logstash:
hosts: ["10.6.66.14:5046"]
shipper:
logging:
files:
關鍵: pattern: '^# User@Host:' 標識新記錄開頭,negate: true + match: after 表示「不匹配該行的內容歸屬於上一條記錄」。
input {
beats {
port => 5046
host => "10.6.66.14"
}
}
filter {
if [type] == "mysqlslowlog" {
grok {
match => {
"message" => "(?m)^#\s+User@Host:\s+%{USER:user}\[[^\]]+\]\s+@\s+(?:(?\S*)\s+)?\[(?:%{IPV4:clientip})?\]\s+Id:\s+%{NUMBER:row_id:int}\n#\s+Query_time:\s+%{NUMBER:query_time:float}\s+Lock_time:\s+%{NUMBER:lock_time:float}\s+Rows_sent:\s+%{NUMBER:rows_sent:int}\s+Rows_examined:\s+%{NUMBER:rows_examined:int}\n\s*(?:use %{DATA:database};\s*\n)?SET\s+timestamp=%{NUMBER:timestamp};\n\s*(?(?\w+)\b.*;)\s*(?:\n#\s+Time)?.*$"
}
}
date {
match => ["timestamp", "UNIX"]
remove_field => ["timestamp"]
}
}
}
Grok 解析欄位: user、clienthost、clientip、row_id、query_time、lock_time、rows_sent、rows_examined、database、sql、action(SELECT/UPDATE/INSERT...)、@timestamp(由 date filter 產生)。
output {
if "_grokparsefailure" in [tags] {
file { path => "/var/log/logstash/grokparsefailure-%{[type]}-%{+YYYY.MM.dd}.log" }
}
if [@metadata][type] in ["mysqlslowlog"] {
elasticsearch {
hosts => ["10.6.66.14:9200"]
sniffing => true
manage_template => false
template_overwrite => true
index => "%{[@metadata][beat]}-%{[type]}-%{+YYYY.MM.dd}"
document_type => "%{[@metadata][type]}"
}
}
}
舊版無 multiline 在 prospector,需在 Logstash Input 階段用 codec => multiline:
input {
beats {
port => 5046
host => "10.6.66.14"
codec => multiline {
pattern => "^# User@Host:"
negate => true
what => "previous"
}
}
}
其餘 Filter/Output 相同。


可建立儀表板:Top 10 耗時 SQL、按用戶/資料庫/時間分布、Rows_examined/Rows_sent 比率分析全表掃描。
dissect 替代簡單結構。SET timestamp 為 UNIX 秒,Logstash date filter 用 UNIX 解析,確保 @timestamp 正確。ignore_above: 256,映射模板需將 sql 欄位設為 text 且 ignore_above 較大或關閉。Rows_examined 遠大於 Rows_sent → 疑似全表掃描/索引缺失,優先優化。