基于 logstash 和 prometheus 的应用异常日志监控告警方案

基于 logstash 和prometheus 的应用异常日志监控告警方案

整体架构与数据流

本方案构建一条日志文本 → 结构化指标 → 告警的管道,核心思路是:Logstash 负责把非结构化日志结构化并落盘,Python 脚本负责把落盘的 JSON 转换为 Prometheus 指标,Prometheus 负责采集与告警评估,Alertmanager 负责通知路由。

图片1

各组件职责边界

组件职责不做什么
filebeat仅采集与转发,无业务解析不做过滤、不做聚合
Logstash解析 timestamp、抽取 error_type、写本地+ES不做计数(每行一个事件)
Python mtail文件尾随读、相似度分组、Prometheus Counter 累加不做告警评估
Prometheus周期 scrape、按 PromQL 评估告警不做日志原文存储
Alertmanager告警分组、抑制、静默、通知不重新评估表达式

技术选型说明

  • 为何不用 mtail:mtail 3.0.8 对 JSON 行解析能力弱、对 multiline stacktrace 支持差,且分组逻辑难表达。Python 直白可控。
  • 为何不用 Loki + Promtail:Loki 适合日志检索而非指标告警,”5 分钟内同错误出现 3 次”这种聚合告警仍需把日志转指标。本方案保留 ES 做原文检索,Python 脚本专注指标化。
  • 为何不用 Vector:Vector 性能更强但学习曲线与运维成本更高;当前场景日志量级(数千 QPS)Logstash 已够用。
  • 为何 Logstash 后还要落本地文件再被 Python 读:解耦 + 缓冲。Logstash 直接暴露 metrics 也行(pipeline-metrics),但无法做”按 message 内容分组”。落文件后 Python 有完整上下文做相似度分组,且文件本身就是缓冲,Python 重启不丢数据。

端到端时序

图片2

基于 logstash 进行异常日志采集

logstash配置-不带默认ERROR的日志采集

以下配置在不需要采集所有ERROR日志的情况下建议优先使用

将以下配置文件中的第一步;第二步;异常日志写入本地文件配置添加到现有的logstash配置文件中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
input {
beats {
port => 5044
}
}

filter {
if [filetype] in ["nginx-access","nginx-error","nginx-apisix"] {
json {
source => "message"
}
mutate {
add_field => { "hostip" => "%{@source}" }
}
ruby {
code => '
ts = event.get("@timestamp")
if ts
event.set("logtime", ts.time.localtime.strftime("%Y-%m-%d %H:%M:%S.%L"))
end
'
}
} else {
grok {
match => ["message","%{TIMESTAMP_ISO8601:logtime}"]
}
mutate {
add_field => { "hostip" => "%{[host][ip][0]}" }
}
}

date {
match => ["logtime","yyyy-MM-dd HH:mm:ss.SSS"]
target => "@timestamp"
timezone => "Asia/Shanghai"
tag_on_failure => ["_dateparsefailure"]
}

ruby {
code => "event.set('local_date', event.get('@timestamp').time.localtime.strftime('%Y.%m.%d'))"
}

# ========== 第一步:匹配具体异常(优先级高)==========
grok {
match => {
#"message" => "(?<error_type>OutOfMemoryError|StackOverflowError|unable to create new native thread|ERROR BusinessException|SQLTimeoutException|ConnectException|SocketTimeoutException|ConnectionLossException|CoordinatorNotAvailableException|CommitFailedException|ElasticsearchTimeoutException|EsRejectedExecutionException|SearchTimeoutException|ReceiveTimeoutTransportException|CacheEncodeException|NotSerializableException|NullPointerException|Exception)"
"message" => "(?<error_type>SQLException|OutOfMemoryError|CacheEncodeException)"
}
tag_on_failure => ["_error_not_found"]
overwrite => ["error_type"]
}

# ========== 第二步:匹配到异常的处理 ==========
if "_error_not_found" not in [tags] {
mutate {
add_tag => ["has_error"]
remove_tag => ["_error_not_found"]
}

ruby {
code => '
require "json"

host = event.get("[host][name]")
if host.nil? || host.empty?
host = event.get("hostip") || "unknown"
end

filetype = event.get("filetype") || "unknown"
app_name = filetype.gsub(/-logs$/, "")

# 使用 grok 匹配到的 error_type,如果没有则设为 UNKNOWN_ERROR
error_type = event.get("error_type")
if error_type.nil? || error_type.empty? || error_type.is_a?(Array)
error_type = "UNKNOWN_ERROR"
elsif error_type.is_a?(Array)
error_type = error_type.first
end

timestamp = event.get("@timestamp").time.localtime.strftime("%Y-%m-%d %H:%M:%S")

json_data = {
"error_type" => error_type,
"host" => host,
"app_name" => app_name,
"timestamp" => timestamp,
"filetype" => filetype,
"message" => event.get("message") || "",
"logtime" => event.get("logtime") || "",
"hostip" => event.get("hostip") || "",
"@timestamp" => event.get("@timestamp").to_s
}

event.set("output_json", json_data.to_json)
'
}
} else {
# 没匹配到异常,清除标记
mutate {
remove_tag => ["_error_not_found"]
}
}
}

output {
# ========== 异常日志写入本地文件(JSON格式)==========
if "has_error" in [tags] {
file {
path => "/data/logs/app-errors-%{+YYYY.MM.dd}.log"
codec => line {
format => "%{output_json}"
}
flush_interval => 1
create_if_deleted => true
}
}

# ========== 写入 Elasticsearch ==========
if "_grokparsefailure" not in [tags] and "_dateparsefailure" not in [tags] {
elasticsearch {
hosts => ["http://192.168.56.105:9200"]
index => "logs-%{filetype}-%{local_date}"
action => "create"
}
}

# ========== 调试输出 ==========
#stdout {
# codec => rubydebug
#}
}

使用filebeat采集以下测试日志

1
2
2025-05-16 09:44:13.190 [http-nio-8480-exec-27] ERROR [54f54bff176f4f7ebcaacefd38d05adc] com.alicp.jetcache.AbstractCache	-jetcache(RedisLettuceCache) PUT error. key=[PZ202506132472916206] com.alicp.jetcache.support.CacheEncodeException: Java Encode error. msg=com.aspire.dccp.common.entity.DccpActivityPrizeDepend
cause by java.io.NotSerializableException: com.aspire.dccp.common.entity.DccpActivityPrizeDepend

建议在 filebeat 配置 multiline:

1
2
3
4
5
6
7
8
filebeat.inputs:
- type: log
paths: [/path/to/app.log]
multiline.type: pattern
multiline.pattern: '^\d{4}-\d{2}-\d{2}' # 以日期开头视为新行
multiline.negate: true
multiline.match: after
multiline.timeout: 5s

输出到本地的日志文件如下:

1
2
3
4
5
6
7
8
9
10
11
{
"error_type": "CacheEncodeException",
"host": "vbox",
"app_name": "java-log",
"timestamp": "2025-05-16 09:44:13",
"filetype": "java-log",
"message": "2025-05-16 09:44:13.190 [http-nio-8480-exec-27] ERROR [54f54bff176f4f7ebcaacefd38d05adc] com.alicp.jetcache.AbstractCache\t-jetcache(RedisLettuceCache) PUT error. key=[PZ202506132472916206] com.alicp.jetcache.support.CacheEncodeException: Java Encode error. msg=com.aspire.dccp.common.entity.DccpActivityPrizeDepend\ncause by java.io.NotSerializableException: com.aspire.dccp.common.entity.DccpActivityPrizeDepend",
"logtime": "2025-05-16 09:44:13.190",
"hostip": "192.168.56.105",
"@timestamp": "2025-05-16T01:44:13.190Z"
}

logstash配置-带默认的ERROR日志采集

以下配置会稍许复杂,为了匹配error_type是我们自定义采集的字段还是默认的ERROR字段,需要采集所有ERROR日志的情况下建议使用,但要综合评估业务error日志量,避免磁盘爆满。

将以下配置文件中的第一步;第二步;第三步;异常日志写入本地文件配置添加到现有的logstash配置文件中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
input {
beats {
port => 5044
}
}

filter {
if [filetype] in ["nginx-access","nginx-error","nginx-apisix"] {
json {
source => "message"
}
mutate {
add_field => { "hostip" => "%{@source}" }
}
ruby {
code => '
ts = event.get("@timestamp")
if ts
event.set("logtime", ts.time.localtime.strftime("%Y-%m-%d %H:%M:%S.%L"))
end
'
}
} else {
grok {
match => ["message","%{TIMESTAMP_ISO8601:logtime}"]
}
mutate {
add_field => { "hostip" => "%{[host][ip][0]}" }
}
}

date {
match => ["logtime","yyyy-MM-dd HH:mm:ss.SSS"]
target => "@timestamp"
timezone => "Asia/Shanghai"
tag_on_failure => ["_dateparsefailure"]
}

ruby {
code => "event.set('local_date', event.get('@timestamp').time.localtime.strftime('%Y.%m.%d'))"
}

# ========== 第一步:匹配具体异常(优先级高)==========
grok {
match => {
"message" => "(?<error_type>SQLException|OutOfMemoryError|CacheEncodeException|StackOverflowError|unable to create new native thread|NotSerializableException|NullPointerException|BusinessException|ConnectException|SocketTimeoutException|ConnectionLossException|CoordinatorNotAvailableException|CommitFailedException|ElasticsearchTimeoutException|EsRejectedExecutionException|SearchTimeoutException|ReceiveTimeoutTransportException)"
}
tag_on_failure => ["_no_specific_error"]
overwrite => ["error_type"]
}

# ========== 第二步:如果没有具体异常,再检查是否包含 ERROR ==========
if "_no_specific_error" in [tags] {
grok {
match => {
"message" => "(?<error_type>ERROR)"
}
tag_on_failure => ["_error_not_found"]
overwrite => ["error_type"]
}
mutate {
remove_tag => ["_no_specific_error"]
}
} else {
mutate {
remove_tag => ["_no_specific_error"]
}
}

# ========== 第三步:匹配到异常的处理 ==========
if "_error_not_found" not in [tags] {
mutate {
add_tag => ["has_error"]
remove_tag => ["_error_not_found"]
}

ruby {
code => '
require "json"

host = event.get("[host][name]")
if host.nil? || host.empty?
host = event.get("hostip") || "unknown"
end

filetype = event.get("filetype") || "unknown"
app_name = filetype.gsub(/-logs$/, "")

# 使用 grok 匹配到的 error_type,如果没有则设为 UNKNOWN_ERROR
error_type = event.get("error_type")
if error_type.nil? || error_type.empty? || error_type.is_a?(Array)
error_type = "UNKNOWN_ERROR"
elsif error_type.is_a?(Array)
error_type = error_type.first
end

timestamp = event.get("@timestamp").time.localtime.strftime("%Y-%m-%d %H:%M:%S")

json_data = {
"error_type" => error_type,
"host" => host,
"app_name" => app_name,
"timestamp" => timestamp,
"filetype" => filetype,
"message" => event.get("message") || "",
"logtime" => event.get("logtime") || "",
"hostip" => event.get("hostip") || "",
"@timestamp" => event.get("@timestamp").to_s
}

event.set("output_json", json_data.to_json)
'
}
} else {
# 没匹配到异常,清除标记
mutate {
remove_tag => ["_error_not_found"]
}
}
}

output {
# ========== 异常日志写入本地文件(JSON格式)==========
if "has_error" in [tags] {
file {
path => "/data/logs/app-errors-%{+YYYY.MM.dd}.log"
codec => line {
format => "%{output_json}"
}
flush_interval => 1
create_if_deleted => true
}
}

# ========== 写入 Elasticsearch ==========
if "_grokparsefailure" not in [tags] and "_dateparsefailure" not in [tags] {
elasticsearch {
hosts => ["http://192.168.56.105:9200"]
index => "logs-%{filetype}-%{local_date}"
action => "create"
}
}

# ========== 调试输出 ==========
#stdout {
# codec => rubydebug
#}
}

使用filebeat采集以下测试日志

1
2025-05-16 09:37:05.976 [http-nio-8480-exec-15] ERROR [950f38537cb64117a3204b8c6a23596f] com.alicp.jetcache.AbstractCache	-jetcache(RedisLettuceCache) PUT error. key=[PZ202401056132126803]

输出到本地的日志文件如下:

1
2
3
4
5
6
7
8
9
10
11
12
tail -f /data/logs/app-errors-2025.05.16.log | jq .
{
"error_type": "ERROR",
"host": "vbox",
"app_name": "java-log",
"timestamp": "2025-05-16 09:37:05",
"filetype": "java-log",
"message": "2025-05-16 09:37:05.976 [http-nio-8480-exec-15] ERROR [950f38537cb64117a3204b8c6a23596f] com.alicp.jetcache.AbstractCache\t-jetcache(RedisLettuceCache) PUT error. key=[PZ202401056132126803]",
"logtime": "2025-05-16 09:37:05.976",
"hostip": "192.168.56.105",
"@timestamp": "2025-05-16T01:37:05.976Z"
}

Python 脚本解析并暴露指标

因为 mtail 最新3.0.8版本对json格式解析能力不足,这时使用python程序解析并暴露指标给prometheus进行采集

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
[root@vbox mtail]# cat error_log.py
#!/usr/bin/env python3
"""Python mtail - 基于相似度的 message 分组"""
import json
import os
import time
import re
from glob import glob
from difflib import SequenceMatcher
from prometheus_client import start_http_server, Counter, Gauge

# ============================================
# 配置
# ============================================
LOG_DIR = "/data/logs/"
STATE_FILE = "./.python_mtail_state.json"
PORT = 3903
SIMILARITY_THRESHOLD = 0.75 # 75% 相似度就算同一组
MAX_GROUPS = 500 # 最大分组数,防止爆炸

# ============================================
# Prometheus 指标
# ============================================
error_log_total = Counter(
'error_log_total',
'Total error count by type, host, app, message_group',
['error_type', 'host', 'app_name', 'message_group']
)

error_log_last_timestamp = Gauge(
'error_log_last_timestamp',
'Last error timestamp',
['error_type', 'host', 'app_name']
)


# ============================================
# 相似度分组逻辑
# ============================================
def normalize_message(msg):
"""标准化 message,去掉可变部分"""
if not msg:
return "unknown"

# 去掉时间戳
msg = re.sub(r'\d{4}[-/]\d{2}[-/]\d{2}\s+\d{2}:\d{2}:\d{2}[.,]?\d*\s*', '', msg)

# 去掉 IP 地址
msg = re.sub(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)?', '<IP>', msg)

# 去掉长数字(ID、端口)
msg = re.sub(r'\b\d{4,}\b', '<NUM>', msg)

# 去掉 UUID
msg = re.sub(r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', '<UUID>', msg)

# 去掉线程名
msg = re.sub(r'\[.*?\]', '', msg)

# 去掉包名/类名
msg = re.sub(r'\b[a-z]+(\.[a-zA-Z]\w+)+\b', '<CLASS>', msg)

# 压缩空格
msg = re.sub(r'\s+', ' ', msg).strip()

return msg


class SimilarityGroupFinder:
"""基于相似度的分组器"""

def __init__(self, threshold=SIMILARITY_THRESHOLD, max_groups=MAX_GROUPS):
self.threshold = threshold
self.max_groups = max_groups
self.groups = {} # normalized_text -> group_name

def find_or_create_group(self, raw_message):
"""找到或创建相似度分组"""
normalized = normalize_message(raw_message)

if not normalized:
return "unknown"

# 如果已经存在完全相同的标准化文本
if normalized in self.groups:
return self.groups[normalized]

# 检查是否达到最大分组数
if len(self.groups) >= self.max_groups:
# 达到上限,返回原始标准化文本
self.groups[normalized] = normalized
return normalized

# 寻找相似的分组
best_match = None
best_score = 0

for existing_norm, group_name in self.groups.items():
score = SequenceMatcher(None, normalized, existing_norm).ratio()
if score > best_score:
best_score = score
best_match = group_name

if best_score >= self.threshold and best_match:
# 相似度足够,归入已有分组
self.groups[normalized] = best_match
return best_match
else:
# 新建分组
self.groups[normalized] = normalized
return normalized


# ============================================
# 日志解析器
# ============================================
class SafeLogParser:
def __init__(self, log_dir=LOG_DIR):
self.log_dir = log_dir
self.positions = {}
self.counters = {} # key: "et|host|app|group" -> count
self.group_finder = SimilarityGroupFinder()
self.state_file = STATE_FILE

self.max_lines_per_cycle = 5000
self.check_interval = 5
self.max_file_age_hours = 48

self.load_state()
self.restore_counters()

def load_state(self):
if os.path.exists(self.state_file):
try:
with open(self.state_file) as f:
data = json.load(f)
self.positions = data.get('positions', {})
self.counters = data.get('counters', {})
self.group_finder.groups = data.get('groups', {})
print(f"[State] Loaded {len(self.positions)} positions, {len(self.counters)} counters, {len(self.group_finder.groups)} groups")
except Exception as e:
print(f"[State] Load failed: {e}")
self.positions = {}
self.counters = {}
self.group_finder.groups = {}
else:
print("[State] No previous state found, starting fresh")

def save_state(self):
current_files = set(glob(os.path.join(self.log_dir, "app-errors-*.log")))
self.positions = {k: v for k, v in self.positions.items() if k in current_files}

data = {
'positions': self.positions,
'counters': self.counters,
'groups': self.group_finder.groups
}

tmp_file = self.state_file + '.tmp'
with open(tmp_file, 'w') as f:
json.dump(data, f)
os.rename(tmp_file, self.state_file)

def restore_counters(self):
MAX_RESTORE = 30000
restored = 0
for key, count in self.counters.items():
if restored >= MAX_RESTORE:
break
parts = key.split('|', 3)
if len(parts) == 4:
error_type, host, app_name, message_group = parts
try:
error_log_total.labels(
error_type=error_type, host=host, app_name=app_name,
message_group=message_group
).inc(count)
restored += 1
except Exception as e:
print(f"[Restore] Error: {e}")
print(f"[Restore] Restored {restored} counters")

def get_log_files(self):
files = sorted(glob(os.path.join(self.log_dir, "app-errors-*.log")))
now = time.time()
return [f for f in files if os.path.getmtime(f) > now - self.max_file_age_hours * 3600]

def parse_new_lines(self):
total_new_lines = 0

for log_file in self.get_log_files():
try:
file_size = os.path.getsize(log_file)
last_pos = self.positions.get(log_file, 0)

if last_pos > file_size:
print(f"[WARN] File truncated: {log_file}")
last_pos = 0

if last_pos == file_size:
continue

with open(log_file, 'r') as f:
f.seek(last_pos)

for i, line in enumerate(f):
if i >= self.max_lines_per_cycle:
break

line = line.strip()
if not line:
continue

try:
data = json.loads(line)

error_type = data.get('error_type', 'unknown')
host = data.get('host', 'unknown')
app_name = data.get('app_name', 'unknown')
raw_message = data.get('message', 'unknown')

# ===== 核心:相似度分组 =====
message_group = self.group_finder.find_or_create_group(raw_message)

counter_key = f'{error_type}|{host}|{app_name}|{message_group}'

self.counters[counter_key] = self.counters.get(counter_key, 0) + 1

error_log_total.labels(
error_type=error_type, host=host, app_name=app_name,
message_group=message_group
).inc()

error_log_last_timestamp.labels(
error_type=error_type, host=host, app_name=app_name
).set(time.time())

total_new_lines += 1

except json.JSONDecodeError:
continue

self.positions[log_file] = f.tell()

except (IOError, PermissionError) as e:
print(f"[ERROR] Cannot read {log_file}: {e}")
continue

if total_new_lines > 0:
print(f"[OK] Processed {total_new_lines} new lines, total groups: {len(self.group_finder.groups)}, total counters: {len(self.counters)}")

self.save_state()

def run_forever(self):
print("=" * 70)
print(" Python mtail - Similarity-based Message Grouping")
print(f" Similarity threshold: {SIMILARITY_THRESHOLD * 100}%")
print(f" Max groups: {MAX_GROUPS}")
print("=" * 70)

while True:
try:
self.parse_new_lines()
time.sleep(self.check_interval)
except KeyboardInterrupt:
print("\n[Shutdown] Saving state...")
self.save_state()
break
except Exception as e:
print(f"[ERROR] {e}")
time.sleep(self.check_interval)


if __name__ == '__main__':
start_http_server(PORT)
print(f"[HTTP] http://0.0.0.0:{PORT}/metrics")

parser = SafeLogParser()
parser.run_forever()

启动

1
2
3
4
5
6
7
8
9
# python3 error_log.py
[HTTP] http://0.0.0.0:3903/metrics
[State] Loaded 2 positions, 6 counters, 12 groups
[Restore] Restored 6 counters
======================================================================
Python mtail - Similarity-based Message Grouping
Similarity threshold: 75.0%
Max groups: 500
======================================================================

prometheus 告警配置

prometheus日志采集配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
scrape_configs:
- job_name: 'error_log_exporter'
static_configs:
- targets: ['192.168.56.105:3903']
labels:
env: prod
region: cn-east-1
scrape_interval: 15s
scrape_timeout: 10s
# 限制超长 message_group 字符串,防止 cardinality 爆炸
metric_relabel_configs:
- source_labels: [message_group]
regex: '(.{0,80}).*'
target_label: message_group
replacement: '${1}'

prometheus告警配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
groups:
- name: error_with_message
interval: 30s
rules:
# 10 分钟内同一 host+app+message_group 出现 >= 3 次
- alert: RepeatedErrorMessage
expr: |
sum by (error_type, host, app_name, message_group) (
increase(error_log_total[10m])
) >= 3
for: 1m
labels:
severity: warning
category: repeated_error
annotations:
summary: "{{ $labels.app_name }} 重复错误: {{ $labels.error_type }}"
description: "{{ $labels.host }} 上的 {{ $labels.app_name }} 在 10 分钟内出现 {{ $value }} 次同类错误\n分组: {{ $labels.message_group }}"

# 10 分钟内出现 >= 10 次:升级为 critical(错误风暴)
- alert: ErrorBurstDetected
expr: |
sum by (error_type, host, app_name, message_group) (
increase(error_log_total[10m])
) >= 10
for: 30s
labels:
severity: critical
category: error_burst
annotations:
summary: "{{ $labels.app_name }} 错误风暴: {{ $labels.error_type }}"
description: "{{ $labels.host }} 上的 {{ $labels.app_name }} 在 10 分钟内出现 {{ $value }} 次同类错误,疑似异常风暴"

# 数据库/连接/超时类错误:5 分钟窗口内出现即告警
- alert: DatabaseOrConnectionError
expr: |
sum by (error_type, host, app_name, message_group) (
increase(error_log_total[5m]{error_type=~".*SQL.*|.*Database.*|.*Connection.*|.*Timeout.*"})
) > 0
for: 0s
labels:
severity: critical
category: infra_error
annotations:
summary: "基础设施类错误: {{ $labels.error_type }}"
description: "{{ $labels.host }}/{{ $labels.app_name }} 检测到 {{ $labels.error_type }}\n分组: {{ $labels.message_group }}"

# JVM 致命错误:立即告警(page=true 用于路由到电话/短信)
- alert: JvmFatalError
expr: |
sum by (error_type, host, app_name, message_group) (
increase(error_log_total[5m]{error_type=~"OutOfMemoryError|StackOverflowError|unable to create new native thread"})
) > 0
for: 0s
labels:
severity: critical
category: jvm_fatal
page: true
annotations:
summary: "JVM 致命错误: {{ $labels.error_type }}"
description: "{{ $labels.host }}/{{ $labels.app_name }} 出现 JVM 致命错误,可能需要立即重启"

# 错误突增:与 1 小时前同比 5 倍以上
- alert: ErrorRateAnomaly
expr: |
sum by (app_name, error_type) (
increase(error_log_total[10m])
)
/
clamp_min(
sum by (app_name, error_type) (
increase(error_log_total[10m] offset 1h)
),
1
) >= 5
and on (app_name, error_type)
sum by (app_name, error_type) (
increase(error_log_total[10m])
) >= 5
for: 5m
labels:
severity: warning
category: anomaly
annotations:
summary: "{{ $labels.app_name }} 错误突增: {{ $labels.error_type }}"
description: "错误量是 1 小时前的 5 倍以上"

# 错误指标采集消失(exporter 挂了)
- alert: ErrorLogExporterDown
expr: up{job="error_log_exporter"} == 0
for: 2m
labels:
severity: critical
category: monitoring
annotations:
summary: "错误日志 exporter 不可达"
description: "{{ $labels.instance }} 的 error_log_exporter 已 2 分钟无响应,监控失效"

Alertmanager 通知路由

告警送达后的分级路由策略:致命 JVM 错误走电话/短信、基础设施错误走钉钉@全员、warning 走钉钉普通群,并启用抑制避免告警风暴。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
route:
receiver: default
group_by: ['alertname', 'app_name', 'error_type']
group_wait: 30s # 同组首条到齐后等 30s 再发,便于聚合
group_interval: 5m # 同组下次发送间隔
repeat_interval: 4h # 同告警重复提醒间隔
routes:
# 致命 JVM 错误走电话/短信,立刻通知
- matchers: ['page="true"']
receiver: sms-phone
group_wait: 0s
repeat_interval: 30m
# 基础设施错误走钉钉@全员
- matchers: ['severity="critical"']
receiver: dingtalk-critical
group_wait: 10s
repeat_interval: 1h
# warning 走钉钉普通群
- matchers: ['severity="warning"']
receiver: dingtalk-normal
repeat_interval: 4h

receivers:
- name: default
webhook_configs:
- url: 'http://your-dingtalk-webhook/default'
send_resolved: true
- name: dingtalk-critical
webhook_configs:
- url: 'http://your-dingtalk-webhook/critical'
send_resolved: true
- name: dingtalk-normal
webhook_configs:
- url: 'http://your-dingtalk-webhook/normal'
send_resolved: true
- name: sms-phone
webhook_configs:
- url: 'http://your-sms-gateway/phone'
send_resolved: true

inhibit_rules:
# JVM 致命错误抑制同主机的同类 warning
- source_matchers: ['category="jvm_fatal"']
target_matchers: ['severity="warning"']
equal: ['host', 'app_name']
# 错误风暴抑制同类 repeated_error
- source_matchers: ['alertname="ErrorBurstDetected"']
target_matchers: ['alertname="RepeatedErrorMessage"']
equal: ['host', 'app_name', 'message_group']

Grafana 看板建议

图片3

关键 PromQL 速查:

看板需求PromQL
各应用错误速率sum by (app_name) (rate(error_log_total[5m]))
Top10 错误分组topk(10, sum by (message_group) (increase(error_log_total[1h])))
错误类型分布sum by (error_type) (increase(error_log_total[1h]))
主机错误热力图sum by (host, app_name) (increase(error_log_total[1h]))
最后错误距今time() - error_log_last_timestamp
各应用总错误数sum by (app_name) (error_log_total)

Grafana 数据链接(Data Link):在 Panel 6 配置 message_group 字段点击跳转 Kibana 的 URL 模板:

1
http://kibana:5601/app/kibana#/discover?_a=(query:(match:(message:query_string:'${__field.value}')))

容量与性能调优

参数默认调优建议说明
check_interval5s10~15s错误日志通常 < 100 QPS,5s 偏激进
max_lines_per_cycle500010000与 check_interval 反比,注意 CPU
MAX_GROUPS500100~200200 已足够覆盖大部分异常类型,更多说明归并不准
SIMILARITY_THRESHOLD0.750.80~0.850.75 太松,相似但不同根因易被合并
max_file_age_hours4824越长 state file 越大,2 天一般够排查
scrape_interval15s15s与 Python check_interval 不必同步,错峰更稳
Prometheus retention15d30d错误指标量小,长保留利于复盘
Logstash flush_interval1s3~5s高错误率时降低 fsync 频率

日志量评估:假设业务峰值 1000 QPS、错误率 0.1% = 1 error/s = 86400/day,按每条 JSON 1KB 计 ≈ 100MB/天。Python 处理毫无压力,瓶颈在 Logstash → ES 的写入与磁盘占用。

磁盘规划(保留 7 天的 app-errors 文件):

  • 单机错误率 1/s:100MB × 7 ≈ 700MB
  • 高峰业务 100/s:10GB × 7 ≈ 70GB(建议加 logrotate)

logrotate 配置 /etc/logrotate.d/app-errors:

1
2
3
4
5
6
7
8
9
/data/logs/app-errors-*.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
copytruncate # Python 还在 tail,用 copytruncate 避免文件句柄失效
}

故障排查表

现象可能原因排查路径
Prometheus 抓不到 metricsPython 端口未起 / 防火墙curl http://host:3903/metrics、ss -lntp | grep 3903
metrics 有但 label 为空Logstash 没匹配到 error_type看 app-errors-*.log 行是否含 error_type 字段
Counter 不增长state file position 错误,文件被截断后未识别看 state file,对比 wc -l 与 position
Counter 双重计数崩溃后 state 与 position 不同步改用 counter._value.set 而非 inc
分组爆炸(group 数持续涨)SIMILARITY_THRESHOLD 太松或正则化失效调高阈值到 0.85,看 normalize_message 输出
告警一直 firing 不消除Counter 单调递增导致表达式写错改用 increase/rate 而非 > N
告警抖动(反复 firing/resolved)for: 太短或窗口边缘抖动拉长 for: 到 2~5m,或加 clamp_min 平滑
Python 进程 OOMgroups dict 无限增长调小 MAX_GROUPS、加 systemd MemoryMax
Logstash 写文件慢flush_interval=1 + 高错误率调到 3~5,或加 buffer
Prometheus 时间线爆炸标签基数过高count(count by (message_group) (error_log_total)) 看基数
错误有但告警不触发for: 太长 / window 不匹配用 PromQL 在 Prometheus UI 手动评估
Alertmanager 告警未送达路由 matchers 不匹配 / webhook 失败看 Alertmanager 日志 /log API

生产部署 Checklist

上线前

  • Python 脚本以 systemd 守护运行,非 root 用户(User=appmon)
  • state file 与日志目录权限分离,state file 路径不与日志混放
  • /data/logs 目录有 logrotate 或 cron 清理,避免磁盘爆满
  • Prometheus 抓取目标加了 env/region 全局标签,便于多环境区分
  • Alertmanager 抑制规则已配(致命错误抑制 warning)
  • Grafana 看板已建且 ES 联动跳转可用
  • 告警通知渠道(钉钉/短信)已联调测试
  • filebeat 多行配置已生效,cause by 行不会丢失上下文
  • Logstash output_json 字段已从 ES 输出剔除

运行中

  • 关注 error_log_total 时间线数:count(error_log_total),超 5 万告警
  • 关注 Python 进程 RSS:systemd MemoryMax,超 512M 告警
  • 关注 Logstash pipeline_latency_seconds,超 1s 告警
  • 关注 app-errors-*.log 文件大小日增长,异常增大说明业务错误率上升
  • 关注 up{job="error_log_exporter"} == 0 告警,exporter 挂掉监控就失效

定期复盘

  • 每周复核 topk 10 message_group,识别需要新增 error_type 关键词的模式
  • 每月清理 state file 中已不存在的日志文件的 position 残留
  • 季度复核告警阈值是否仍匹配业务规模(业务量翻倍时阈值需同步调整)
  • 季度复核抑制规则是否仍合理,避免过度抑制导致漏报

后续可改进路线

阶段目标关键动作
短期控制基数,提升扩展性拆 generic/specific metric、降 MAX_GROUPS、加 SimHash
长期统一可观测性栈评估 Vector/Loki/OTel,纳入公司整体可观测性平台
-------------本文结束感谢您的阅读-------------