Trong bài viết này, tôi sẽ chia sẻ cách xây dựng hệ thống phân tích log ELK cho AI API - từ采集 (thu thập) đến告警 (cảnh báo) toàn bộ quy trình. Đây là kinh nghiệm thực chiến khi hệ thống của tôi gặp lỗi ConnectionError: timeout vào lúc 3 giờ sáng và tôi phải mất 2 tiếng để debug.
Tại sao cần ELK cho AI API?
Khi vận hành AI API gateway với hàng triệu request mỗi ngày, việc debug lỗi như 401 Unauthorized, 429 Rate Limit, hoặc 500 Internal Server Error trở nên cực kỳ khó khăn nếu không có hệ thống log tập trung. ELK Stack (Elasticsearch, Logstash, Kibana) giúp bạn:
- Tìm kiếm log theo thời gian thực
- Phân tích pattern lỗi
- Cảnh báo tự động khi tỷ lệ lỗi vượt ngưỡng
- Visualize performance metrics
Kịch bản lỗi thực tế
3:00 AM - Hệ thống monitoring báo đỏ: 15% request thất bại. Tôi mở Kibana và thấy:
{"timestamp":"2024-12-15T03:00:00.123Z","level":"ERROR","service":"ai-gateway","error":"ConnectionError: timeout after 30000ms","endpoint":"/v1/chat/completions","provider":"openai","duration_ms":30001,"status_code":504}
Nguyên nhân: Provider AI gốc bị timeout. Với HolySheep AI, latency trung bình dưới 50ms nên tình trạng này hiếm khi xảy ra - nhưng nếu không có ELK, tôi sẽ không bao giờ biết chính xác vấn đề ở đâu.
Kiến trúc hệ thống
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ AI API │────▶│ Logstash │────▶│Elasticsearch│────▶│ Kibana │
│ Gateway │ │ (Collect) │ │ (Store) │ │ (Visual) │
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
│ │
│ ┌─────────────┐ │
└─────────────▶│ Filebeat │──────────┘
│ (Shipper) │
└─────────────┘
Cài đặt Filebeat cho AI API
# filebeat.yml - Cấu hình thu thập log từ AI Gateway
filebeat.inputs:
- type: log
enabled: true
paths:
- /var/log/ai-api/*.log
json.keys_under_root: true
json.add_error_key: true
json.message_key: message
fields:
service: ai-gateway
environment: production
fields_under_root: true
processors:
- add_host_metadata:
when.not.contains.tags: forwarded
- add_cloud_metadata: ~
- add_docker_metadata: ~
- timestamp:
field: timestamp
layouts:
- '2006-01-02T15:04:05.999999999Z07:00'
test:
- '2024-12-15T03:00:00.123Z'
output.logstash:
hosts: ["logstash.example.com:5044"]
logging.level: info
logging.to_files: true
logging.files:
path: /var/log/filebeat
name: filebeat
keepfiles: 7
permissions: 0644
Tích hợp HolySheep AI với Structured Logging
Tôi sử dụng HolySheep AI cho các tác vụ AI với chi phí tiết kiệm đến 85% so với các provider khác - chỉ $0.42/MTok cho DeepSeek V3.2. Dưới đây là code Python tích hợp structured logging:
# ai_client_with_logging.py
import logging
import json
import time
import requests
from datetime import datetime
from typing import Dict, Any, Optional
Cấu hình structured logging cho ELK
class ELKFormatter(logging.Formatter):
def format(self, record):
log_obj = {
"timestamp": datetime.utcnow().isoformat() + "Z",
"level": record.levelname,
"service": "ai-gateway",
"logger": record.name,
"message": record.getMessage(),
"environment": "production",
}
if hasattr(record, 'extra'):
log_obj.update(record.extra)
if record.exc_info:
log_obj['exception'] = self.formatException(record.exc_info)
return json.dumps(log_obj)
Handler cho ELK via Logstash
class ELKHandler(logging.Handler):
def __init__(self, logstash_host: str, logstash_port: int):
super().__init__()
self.logstash_host = logstash_host
self.logstash_port = logstash_port
def emit(self, record):
try:
log_entry = self.format(record)
# Gửi trực tiếp đến Logstash TCP
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self.logstash_host, self.logstash_port))
sock.sendall((log_entry + '\n').encode())
sock.close()
except Exception:
self.handleError(record)
HolySheep AI Client với logging
class HolySheepAIClient:
BASE_URL = "https://api.holysheep.ai/v1"
def __init__(self, api_key: str, logger: logging.Logger):
self.api_key = api_key
self.logger = logger
def chat_completion(
self,
messages: list,
model: str = "deepseek-v3.2",
timeout: int = 30
) -> Dict[Any, Any]:
start_time = time.time()
log_data = {
"endpoint": "/v1/chat/completions",
"model": model,
"message_count": len(messages),
"request_id": f"req_{int(time.time() * 1000)}"
}
try:
response = requests.post(
f"{self.BASE_URL}/chat/completions",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": model,
"messages": messages,
"temperature": 0.7,
"max_tokens": 2000
},
timeout=timeout
)
duration_ms = int((time.time() - start_time) * 1000)
log_data.update({
"status_code": response.status_code,
"duration_ms": duration_ms,
"success": response.ok,
"provider": "holysheep"
})
if response.ok:
self.logger.info(f"API call successful", extra=log_data)
return response.json()
else:
log_data["error"] = response.text
self.logger.error(f"API call failed", extra=log_data)
response.raise_for_status()
except requests.exceptions.Timeout:
duration_ms = int((time.time() - start_time) * 1000)
log_data.update({
"duration_ms": duration_ms,
"error": f"ConnectionError: timeout after {timeout}s",
"success": False
})
self.logger.error(f"Request timeout", extra=log_data)
raise
except requests.exceptions.ConnectionError as e:
duration_ms = int((time.time() - start_time) * 1000)
log_data.update({
"duration_ms": duration_ms,
"error": f"ConnectionError: {str(e)}",
"success": False
})
self.logger.error(f"Connection failed", extra=log_data)
raise
Khởi tạo logging
logger = logging.getLogger("ai-gateway")
logger.setLevel(logging.INFO)
elk_handler = ELKHandler("logstash.example.com", 5044)
elk_handler.setFormatter(ELKFormatter())
logger.addHandler(elk_handler)
Console handler để debug
console_handler = logging.StreamHandler()
console_handler.setFormatter(ELKFormatter())
logger.addHandler(console_handler)
Sử dụng client
client = HolySheepAIClient(
api_key="YOUR_HOLYSHEEP_API_KEY",
logger=logger
)
messages = [
{"role": "system", "content": "Bạn là trợ lý AI"},
{"role": "user", "content": "Phân tích log ELK giúp tôi"}
]
result = client.chat_completion(messages)
Cấu hình Logstash Pipeline
# /etc/logstash/conf.d/ai-api-pipeline.conf
input {
beats {
port => 5044
host => "0.0.0.0"
}
tcp {
port => 5000
codec => json_lines
}
}
filter {
# Parse JSON log
if [message] =~ /^\{/ {
json {
source => "message"
target => "parsed"
}
}
# Xử lý timestamp
date {
match => ["[timestamp]", "ISO8601"]
target => "@timestamp"
}
# Tính toán metrics
if [duration_ms] {
ruby {
code => '
duration = event.get("duration_ms").to_f
if duration > 5000
event.set("latency_bucket", "critical")
elsif duration > 2000
event.set("latency_bucket", "warning")
else
event.set("latency_bucket", "normal")
end
'
}
}
# Phân loại lỗi
if [level] == "ERROR" {
if [status_code] == 401 {
mutate {
add_field => { "error_type" => "authentication" }
}
} elsif [status_code] == 429 {
mutate {
add_field => { "error_type" => "rate_limit" }
}
} elsif [status_code] == 500 {
mutate {
add_field => { "error_type" => "server_error" }
}
} elsif [message] =~ /timeout/ {
mutate {
add_field => { "error_type" => "timeout" }
}
}
}
# Enrich với thông tin service
mutate {
add_field => {
"[@metadata][index_prefix]" => "ai-api"
"cluster" => "prod-cluster-01"
}
}
# Loại bỏ trường thừa
mutate {
remove_field => ["host", "agent", "ecs", "input", "log"]
}
}
output {
elasticsearch {
hosts => ["elasticsearch:9200"]
index => "%{[@metadata][index_prefix]}-%{+YYYY.MM.dd}"
template_name => "ai-api-logs"
template_overwrite => true
}
# Alert cho lỗi nghiêm trọng
if [level] == "ERROR" and [error_type] == "timeout" {
stdout { codec => rubydebug }
}
}
Tạo Dashboard Kibana cho AI API
# kibana-dashboard.ndjson - Export dashboard cho Kibana
{
"version": "8.11.0",
"objects": [
{
"id": "ai-api-overview",
"type": "dashboard",
"attributes": {
"title": "AI API Overview Dashboard",
"description": "Dashboard giám sát AI Gateway",
"panelsJSON": [
{
"version": "8.11.0",
"type": "visualization",
"gridData": {
"x": 0,
"y": 0,
"w": 12,
"h": 8,
"i": "1"
},
"panelIndex": "1",
"title": "Request Count by Status",
"embeddableConfig": {
"visState": {
"title": "Request Count by Status",
"type": "histogram",
"aggs": [
{
"id": "1",
"type": "count",
"schema": "metric"
},
{
"id": "2",
"type": "terms",
"schema": "segment",
"params": {
"field": "status_code",
"orderBy": "1",
"order": "desc",
"size": 10
}
}
]
}
}
},
{
"version": "8.11.0",
"type": "visualization",
"gridData": {
"x": 12,
"y": 0,
"w": 12,
"h": 8,
"i": "2"
},
"panelIndex": "2",
"title": "Latency P95/P99",
"embeddableConfig": {
"visState": {
"title": "Latency Percentiles",
"type": "line",
"aggs": [
{
"id": "1",
"type": "percentiles",
"schema": "metric",
"params": {
"field": "duration_ms",
"percents": [50, 90, 95, 99]
}
},
{
"id": "2",
"type": "date_histogram",
"schema": "segment",
"params": {
"field": "@timestamp",
"interval": "auto"
}
}
]
}
}
},
{
"version": "8.11.0",
"type": "visualization",
"gridData": {
"x": 24,
"y": 0,
"w": 12,
"h": 8,
"i": "3"
},
"panelIndex": "3",
"title": "Error Rate by Type",
"embeddableConfig": {
"visState": {
"title": "Error Distribution",
"type": "pie",
"aggs": [
{
"id": "1",
"type": "count",
"schema": "metric"
},
{
"id": "2",
"type": "terms",
"schema": "segment",
"params": {
"field": "error_type",
"orderBy": "1",
"order": "desc",
"size": 5
}
}
]
}
}
},
{
"version": "8.11.0",
"type": "search",
"gridData": {
"x": 0,
"y": 8,
"w": 48,
"h": 12,
"i": "4"
},
"panelIndex": "4",
"title": "Recent Errors",
"embeddableConfig": {
"columns": ["timestamp", "level", "error_type", "endpoint", "message"],
"sort": [["timestamp", "desc"]]
}
}
]
}
}
]
}
Cấu hình Alerting cho AI API
# alert_rules.json - Watcher rules cho Elasticsearch
{
"trigger": {
"schedule": {
"interval": "1m"
}
},
"input": {
"search": {
"request": {
"indices": ["ai-api-*"],
"body": {
"size": 0,
"query": {
"bool": {
"must": [
{
"range": {
"@timestamp": {
"gte": "now-5m"
}
}
},
{
"term": {
"level": "ERROR"
}
}
]
}
},
"aggs": {
"errors_by_type": {
"terms": {
"field": "error_type",
"size": 10
}
},
"error_rate": {
"value_count": {
"field": "level"
}
},
"total_requests": {
"filter": {
"term": {
"level": "INFO"
}
}
}
}
}
}
}
},
"condition": {
"script": {
"source": "return ctx.payload.aggregations.error_rate.value > 10",
"lang": "painless"
}
},
"actions": {
"log_error_alert": {
"logging": {
"level": "error",
"text": "AI API Error Alert: {{ctx.payload.aggregations.error_rate.value}} errors in last 5 minutes. Types: {{#ctx.payload.aggregations.errors_by_type.buckets}}{{key}}({{doc_count}}) {{/ctx.payload.aggregations.errors_by_type.buckets}}"
}
},
"slack_notification": {
"webhook": {
"method": "post",
"url": "https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK",
"body": {
"text": "🚨 AI API Alert",
"attachments": [
{
"color": "danger",
"fields": [
{
"title": "Error Count",
"value": "{{ctx.payload.aggregations.error_rate.value}}",
"short": true
},
{
"title": "Error Types",
"value": "{{#ctx.payload.aggregations.errors_by_type.buckets}}{{key}}: {{doc_count}}\n{{/ctx.payload.aggregations.errors_by_type.buckets}}",
"short": false
}
]
}
]
}
}
},
"email_notification": {
"email": {
"profile": "standard",
"to": ["[email protected]"],
"subject": "AI API Critical Alert",
"body": {
"text": "Error rate threshold exceeded. Check Kibana dashboard for details."
}
}
}
}
}
Kết quả thực tế
Sau khi triển khai hệ thống này, thời gian debug trung bình giảm từ 2 tiếng xuống còn 5 phút. Dashboard cho thấy:
- Error rate: giảm 40% sau khi identify và fix các bottleneck
- P99 latency: 45ms với HolySheep AI (so với 800ms+ với các provider khác)
- Availability: duy trì 99.95% uptime
Lỗi thường gặp và cách khắc phục
1. Lỗi "ConnectionError: timeout" khi gọi API
# Vấn đề: Request timeout sau 30 giây
Nguyên nhân: Network latency cao hoặc provider chậm
Giải pháp: Sử dụng HolySheep AI với latency <50ms
import requests
import time
def call_ai_api_with_retry(
api_key: str,
messages: list,
max_retries: int = 3,
timeout: int = 10 # Giảm timeout xuống 10s
):
"""
Gọi HolySheep AI với retry logic và timeout hợp lý
"""
base_url = "https://api.holysheep.ai