基础篇
进阶篇
高频篇
精选篇
手写篇
面经篇
AI 篇
原理篇
每日一题
小程序题库
  • 知识卡片碎片时间过考点
  • 场景篇按分类整理的大前端场景考点
  • 历年面经按年份追踪真实考点
  • 算法题库NEW在线编码即时判题
  • 专项自测100 题快速查漏
  • 前端基础
    • HTTP从报文一路讲到 HTTPS
    • 浏览器渲染、事件循环、进程
    • 计算机基础Linux、网络、操作系统
  • 进阶专项
    • 设计模式23 种模式怎么用
    • 前端系统进阶学习大型项目工程化
    • 前端综合文章长期沉淀的实践文
  • 工程与工具
    • Node学习指南从环境搭建到服务端
    • NPM工作流script、依赖与发布
    • Docker容器化部署上手
    • Canvas图形与动画实战
  • 路线与导图
    • 思维导图知识点全景图
    • 学习路线按图索骥不跑偏
  • 动态
    • 公众号动态公众号历史文章
    • 博客动态站长的技术博客
    • 开发者导航常用工具与文档站
    • AI 热点每日 AI 资讯与动向
AI 工作台NEW
旧版
AIHT
内容
精选全部 AI 动态热点榜AI 日报收藏
分类
模型行业编程产品技术观点开源
更多
Agent 接入
返回首页开发者导航
AIHT
精选 / 资讯详情
8.0
热点
AI SCORE
技术实践2026-08-20 07:34

用LLM构建分布式系统诊断工具:日志分析实战

dev.to · AI#LLM#分布式系统#日志分析
Editor brief · 编辑速览

用Python模拟微服务故障场景,通过OpenAI SDK驱动LLM自动定位跨服务错误根因。

文章思维导图
Knowledge map
拖拽缩放
Full translation

完整中文译文

我们要构建的是一个分布式日志诊断工具——一个用 LLM 来定位跨服务故障的小型 Python Agent。当在十个容器上 tail 日志已经无法满足需求时,这个工具就能派上用场。

依赖安装:

pip install openai

还需要一个来自 https://portal.oxlo.ai 的 Oxlo.ai API Key。

步骤 1:模拟微服务集群

需要一个被监控对象,所以创建了三个假服务。payment-service 被配置为故障状态,这样就能有一个真实的分布式故障可供检测。

import random
from datetime import datetime, timedelta

class ServiceNode:
    def __init__(self, name, failure_mode=False):
        self.name = name
        self.healthy = True
        self.logs = []
        self.failure_mode = failure_mode

    def generate_logs(self, count=5):
        self.logs = []
        for i in range(count):
            ts = (datetime.utcnow() - timedelta(seconds=i * 15)).isoformat()
            if self.failure_mode:
                msg = f"{ts} ERROR {self.name} connection reset by peer, upstream timeout"
                self.healthy = False
            else:
                msg = f"{ts} INFO {self.name} health=OK req_id={random.randint(1000, 9999)}"
            self.logs.append(msg)
        return "\n".join(self.logs)

nodes = [
    ServiceNode("user-service"),
    ServiceNode("payment-service", failure_mode=True),
    ServiceNode("notification-service"),
]

步骤 2:从所有节点收集日志

协调器从每个节点收集最新日志,汇聚成一个统一的上下文块,这样模型就能看到整个集群的状态。

def collect_cluster_state(nodes):
    blocks = []
    for node in nodes:
        logs = node.generate_logs(count=6)
        blocks.append(f"--- {node.name} ---\n{logs}")
    return "\n\n".join(blocks)

cluster_state = collect_cluster_state(nodes)
print(cluster_state)

步骤 3:定义 System Prompt

需要结构化的推理,而不是散文式的输出。这个 prompt 告诉模型扮演 SRE 角色,并以我们可解析的固定格式回复。

SYSTEM_PROMPT = """You are a distributed systems SRE. You are given logs from multiple microservices.
Analyze the logs to identify the root cause. Respond in this exact format:

Root Cause: 
Affected Services: 
Recommended Action: 
Confidence: 

Be concise. If no issue is found, state "No issue detected"."""

步骤 4:用 Oxlo.ai 进行诊断

将完整的日志包发送给 Oxlo.ai 上的 Llama 3.3 70B。由于 Oxlo.ai 采用扁平化的按请求定价,从三个服务拉取六行日志并不会增加调用成本。当从三个服务扩展到三十个服务时,这就很重要了。

from openai import OpenAI

client = OpenAI(base_url="https://api.oxlo.ai/v1", api_key="YOUR_OXLO_API_KEY")

def diagnose(state: str) -> str:
    response = client.chat.completions.create(
        model="llama-3.3-70b",
        messages=[
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": state},
        ],
    )
    return response.choices[0].message.content

diagnosis = diagnose(cluster_state)
print(diagnosis)

步骤 5:根据诊断结果执行操作

最后,解析结构化的回复结果,对模拟集群执行建议的操作。在生产环境中,这个 hook 会调用 kubectl 或你的容器编排工具。

def act(diagnosis: str, nodes):
    affected = []
    action = "none"
    for line in diagnosis.splitlines():
        if line.startswith("Affected Services:"):
            raw = line.split(":", 1)[1]
            affected = [s.strip() for s in raw.split(",")]
        if line.startswith("Recommended Action:"):
            action = line.split(":", 1)[1].strip().lower()

    for node in nodes:
        if node.name in affected and action == "restart":
            node.healthy = True
            node.failure_mode = False
            node.logs = []
            print(f"Executed restart on {node.name}")

act(diagnosis, nodes)

print("\nPost-recovery state:")
print(collect_cluster_state(nodes))

将所有代码保存到 diagnostician.py,替换 YOUR_OXLO_API_KEY,然后运行:

python diagnostician.py

输出结果:

--- user-service ---
2024-05-20T14:12:00 INFO user-service health=OK req_id=4821
2024-05-20T14:11:45 INFO user-service health=OK req_id=3912
...

--- payment-service ---
2024-05-20T14:12:00 ERROR payment-service connection reset by peer, upstream timeout
2024-05-20T14:11:45 ERROR payment-service connection reset by peer, upstream timeout
...

--- notification-service ---
2024-05-20T14:12:00 INFO notification-service health=OK req_id=9912
...

Root Cause: payment-service is failing due to upstream timeouts likely caused by connection resets.
Affected Services: payment-service
Recommended Action: restart
Confidence: high

Executed restart on payment-service

Post-recovery state:
--- payment-service ---
2024-05-20T14:12:45 INFO payment-service health=OK req_id=5543
...

下一步

接下来可以将 ServiceNode 类连接到真实的 HTTP 健康检查端点,这样 Agent 就能监控真实的容器了。如果想更进一步,可以将日志通过 Oxlo.ai 的 embedding 端点发送,存储到向量数据库中,这样 Agent 在诊断前就能检索相似的历史故障案例。

Original source

本文由 AI 翻译整理,来源 dev.to · AI,原文版权归原作者所有。

阅读原文
上一篇
Sentry Python SDK 内存泄漏:三人(包含 AI)同犯同一错误的根因分析
下一篇
Google Chat推出Gemini助手:可跨Gmail/Drive/Calendar执行任务

资讯速览

dev.to · AI · 2026-08-20 07:34

AI 评分 8.0 / 10

相关标签

#LLM#分布式系统#日志分析

继续阅读

  • 将扁平日志重构为因果执行树:现代 AI Agent 调试实战
  • Sentry Python SDK 内存泄漏:三人(包含 AI)同犯同一错误的根因分析
  • Google Chat推出Gemini助手:可跨Gmail/Drive/Calendar执行任务
  • 用 smolvm 为 Python/JS 代码构建轻量安全沙箱
  • ReAct模式深度解析:让LLM Agent思考后再行动