[← 第 08 章](/openclaw-tutorial/08-%E5%8D%95%20Gateway%20%E5%A4%9A%20Agent%20%E9%85%8D%E7%BD%AE%E4%B8%8E%E7%AE%A1%E7%90%86.html) · [📑 目录](/openclaw-tutorial/) · [📋 大纲](/openclaw-tutorial/OUTLINE.html) · [第 10 章 →](/openclaw-tutorial/10-%E6%8C%81%E7%BB%AD%E9%9B%86%E6%88%90%E4%B8%8E%E7%9F%A5%E8%AF%86%E5%BA%93%E5%90%8C%E6%AD%A5.html)

第 9 章:故障排查与日志分析

difficulty time chapter

难度: ⭐⭐ 基础 预计阅读: 18 分钟 前置章节: 第 1-2 章

本章提供 OpenClaw 故障排查的系统方法,包括诊断工具、日志分析和常见问题的完整解决方案。掌握这些技能,你可以快速定位并解决 99% 的运行问题。

📑 本章目录


9.1 诊断工具

OpenClaw doctor

OpenClaw 内置了一键诊断命令,可快速检测环境和配置问题:

openclaw doctor        # 全面诊断
openclaw doctor --fix  # 自动修复已知问题
openclaw doctor --json # 输出 JSON 格式(适合脚本调用)

检查项目包括:

检查项 说明 自动修复
Node.js 版本 需要 >= 18
Gateway 服务状态 进程是否运行 ✅ 重启
配置文件格式 JSON 语法有效性 ✅ 使用备份恢复
Skills 加载状态 SKILL.md 格式检查
通道连接状态 飞书/Slack 连通性 ✅ 重连
磁盘空间 剩余空间检查
网络连通性 AI 模型 API 连通

手动检查清单

# 检查 Gateway 进程
ps aux | grep openclaw
systemctl status openclaw-gateway --user

# 检查端口占用
lsof -i :18789
ss -tlnp | grep 18789

# 检查配置文件语法
python3 -m json.tool ~/.openclaw/openclaw.json

# 检查磁盘空间
df -h ~/.openclaw/
du -sh ~/.openclaw/*/

自动化健康检查脚本

创建定期运行的健康检查脚本,主动发现问题:

#!/bin/bash
# health-check.sh — OpenClaw 自动健康检查
set -e

echo "=== OpenClaw 健康检查 $(date) ==="

# 1. 检查 Gateway 进程
if pgrep -f "openclaw" > /dev/null; then
  echo "✅ Gateway 进程正常"
else
  echo "❌ Gateway 未运行,尝试重启..."
  openclaw gateway start
fi

# 2. 检查端口
if ss -tlnp | grep -q 18789; then
  echo "✅ 端口 18789 正常监听"
else
  echo "❌ 端口 18789 未监听"
fi

# 3. 检查磁盘空间
DISK_USAGE=$(df -h ~/.openclaw/ | tail -1 | awk '{print $5}' | tr -d '%')
if [ "$DISK_USAGE" -lt 90 ]; then
  echo "✅ 磁盘使用 ${DISK_USAGE}%"
else
  echo "⚠️  磁盘使用 ${DISK_USAGE}%,建议清理"
fi

# 4. 检查配置文件
if python3 -m json.tool ~/.openclaw/openclaw.json > /dev/null 2>&1; then
  echo "✅ 配置文件语法正确"
else
  echo "❌ 配置文件 JSON 格式错误"
fi

echo "=== 检查完成 ==="

9.2 日志系统详解

日志位置

~/.openclaw/logs/
├── gateway.log          # Gateway 主日志
├── config-audit.jsonl   # 配置审计日志
├── agent-sessions/      # Agent 会话日志(每次对话一个文件)
└── cron/               # Cron 任务执行日志

查看日志

# 实时跟踪 Gateway 日志
openclaw logs --follow

# systemd 服务日志
journalctl --user -u openclaw-gateway -f

# 只看错误
journalctl --user -u openclaw-gateway --priority=err

# 查最近 1 小时
journalctl --user -u openclaw-gateway --since "1 hour ago"

# 查看配置审计记录
tail -20 ~/.openclaw/logs/config-audit.jsonl | python3 -m json.tool

日志级别说明

级别 说明 典型场景 日志量
DEBUG 详细调试信息 开发调试时使用 极高
INFO 常规运行信息 请求处理、任务启动 中等
WARN 警告但不影响运行 API 限速、降级处理 较少
ERROR 错误,需要关注 API 调用失败、超时
FATAL 致命错误,服务终止 端口冲突、配置损坏 极少

调整日志级别

# 调高日志级别(排查问题时使用)
openclaw config set logLevel debug

# 恢复正常级别
openclaw config set logLevel info

日志分析实用命令

# 统计最近一天各级别日志数量
journalctl --user -u openclaw-gateway --since "1 day ago" --no-pager | \
  grep -oP '(DEBUG|INFO|WARN|ERROR|FATAL)' | sort | uniq -c | sort -rn

# 提取所有错误信息的时间线
journalctl --user -u openclaw-gateway --priority=err --since "7 days ago" \
  --no-pager -o short-iso | tail -50

# 统计 Cron 任务执行成功/失败次数
for f in ~/.openclaw/cron/runs/*.jsonl; do
  status=$(tail -1 "$f" | python3 -c "import sys,json; print(json.load(sys.stdin).get('status','unknown'))" 2>/dev/null)
  echo "$(basename $f): $status"
done | sort -t: -k2 | uniq -c -f1

使用 Python 解析结构化日志

#!/usr/bin/env python3
# parse-audit-log.py — 解析配置审计日志
import json
from datetime import datetime

log_file = "~/.openclaw/logs/config-audit.jsonl"
with open(log_file.replace("~", __import__("os").path.expanduser("~"))) as f:
    for line in f:
        entry = json.loads(line.strip())
        ts = entry.get("timestamp", "unknown")
        action = entry.get("action", "unknown")
        detail = entry.get("detail", "")
        print(f"[{ts}] {action}: {detail}")

9.3 常见故障与解决方案

故障一:Gateway 无法启动

症状openclaw gateway start 后立即退出

# 步骤 1: 检查端口
lsof -i :18789
# 如果有其他程序占用,kill 或改端口

# 步骤 2: 检查配置
cat ~/.openclaw/openclaw.json | python3 -m json.tool
# 如果 JSON 无效,用备份恢复:
cp ~/.openclaw/openclaw.json.bak ~/.openclaw/openclaw.json

# 步骤 3: 重新安装服务
openclaw daemon install --force
openclaw gateway start

故障二:Agent 无响应

症状:发消息到飞书后 Agent 没有回复

# 检查 Gateway 连接状态
openclaw gateway status --deep

# 检查 AI 模型可用性
curl -s https://api.openai.com/v1/models -H "Authorization: Bearer $OPENAI_KEY" | head

# 检查飞书通道连接
openclaw channels status

# 重启 Gateway
openclaw gateway restart

故障三:Skill 加载失败

症状:特定技能无法使用

# 验证 SKILL.md 格式
head -20 ~/.openclaw/workspace/skills/<name>/SKILL.md

# 检查 YAML front matter 是否有效
python3 -c "
import yaml
with open('SKILL.md') as f:
    content = f.read()
    # 提取 front matter
    parts = content.split('---')
    if len(parts) >= 3:
        meta = yaml.safe_load(parts[1])
        print('Valid:', meta.get('name'))
"

# 检查 _meta.json
python3 -m json.tool ~/.openclaw/workspace/skills/<name>/_meta.json

# 全面诊断
openclaw doctor

故障四:Cron 任务不执行

症状:定时任务没有按预期运行

# 检查 cron 配置
python3 -m json.tool ~/.openclaw/cron/jobs.json

# 检查任务状态
python3 -c "
import json
jobs = json.load(open('$HOME/.openclaw/cron/jobs.json'))
for job in jobs['jobs']:
    state = job.get('state', {})
    print(f'{job[\"name\"]}: enabled={job[\"enabled\"]}, '
          f'lastStatus={state.get(\"lastStatus\", \"never\")}, '
          f'errors={state.get(\"consecutiveErrors\", 0)}')
"

故障排查决策树

症状 首先检查 若无效则 最终手段
Gateway 不启动 端口占用 lsof -i :18789 配置文件 python3 -m json.tool openclaw daemon install --force
Agent 无响应 Gateway 状态 openclaw gateway status AI API 连通 curl 重启 openclaw gateway restart
Skill 不工作 SKILL.md 存在性 YAML 格式验证 openclaw doctor --fix
Cron 不执行 jobs.json 有效性 enabled 是否为 true 检查 consecutiveErrors
消息发不出 通道状态 openclaw channels status Token 有效性 重新配对设备

9.4 性能优化

当 OpenClaw 在生产环境中稳定运行后,性能优化成为提升用户体验的关键。本节从内存、响应速度和磁盘三个维度介绍常见的优化方法。建议先用 openclaw doctor 确认无功能性故障后,再进行性能调优。

Gateway 内存优化

# 查看当前内存占用
ps -o pid,vsz,rss,comm -p $(pgrep -f openclaw)

# 限制 Node.js 内存
NODE_OPTIONS="--max-old-space-size=512" openclaw gateway start

响应速度优化

优化项 方法 效果
AI 模型选择 简单任务用小模型 响应快 2-5x
Skill 懒加载 只在调用时加载 减少启动时间
记忆裁剪 定期归档旧记忆 减少上下文长度
并发限制 设置 maxConcurrent 避免过载

磁盘清理

# 查看各目录占用
du -sh ~/.openclaw/*/

# 清理历史会话
find ~/.openclaw/agents/*/sessions/ -mtime +30 -delete

# 清理 Cron 运行记录
find ~/.openclaw/cron/runs/ -mtime +7 -delete

# 压缩日志
gzip ~/.openclaw/logs/*.log.old

性能监控配置

可将性能监控配置为 Cron 任务,定期收集指标:

{
  "name": "性能监控",
  "schedule": {"kind": "cron", "expr": "*/30 * * * *"},
  "payload": {
    "kind": "agentTurn",
    "message": "检查 Gateway 内存占用和磁盘空间,如果异常则告警"
  }
}

进阶:深入理解日志架构

OpenClaw 的日志系统采用分层架构,理解其原理能帮助你更高效地定位问题。

日志分层模型

层次 文件位置 内容 保留策略
系统层 ~/.openclaw/logs/gateway.log Gateway 启停、端口绑定、进程信号 7 天轮转
Agent 层 ~/.openclaw/agents/*/sessions/ 会话日志、工具调用、AI 响应 按会话保留
Cron 层 ~/.openclaw/cron/runs/*.jsonl 定时任务执行记录 30 天自动清理
审计层 ~/.openclaw/logs/config-audit.jsonl 配置变更、权限操作 永久保留

结构化日志解析技巧

利用 jq 可以对结构化日志进行复杂查询,显著提升排查效率:

# 统计过去 24h 各级别日志数量
cat ~/.openclaw/logs/gateway.log | \
  jq -r '.level' 2>/dev/null | sort | uniq -c | sort -rn

# 查看 Cron 任务失败历史(最近 10 条)
for f in ~/.openclaw/cron/runs/*.jsonl; do
  tail -1 "$f" | jq -r 'select(.status=="error") | "\(.timestamp) \(.error)"' 2>/dev/null
done | tail -10

# 分析 Agent 工具调用频率
grep -h '"tool"' ~/.openclaw/agents/main/sessions/*.jsonl 2>/dev/null | \
  jq -r '.tool' | sort | uniq -c | sort -rn | head -10

注意事项与常见误区

在故障排查过程中,以下几个常见误区值得警惫:

误区 说明 正确做法
直接重启解决一切 重启可能掩盖根因,问题会反复出现 先查日志确认原因,再决定是否重启
忽略 WARNING 日志 WARNING 级别往往是故障的前兆 定期检查 WARNING,尤其是“连接超时”和“磁盘空间不足”
DEBUG 日志长期开启 每天级产生 GB 级日志,影响磁盘和 IO 排查完立即恢复 openclaw config set logLevel info
只看最后一行日志 错过了联动故障的上下文 使用 journalctl --since 查看时间范围内的完整日志

最佳实践:在生产环境中,建议配置 Cron 任务定期运行 openclaw doctor,将结果通过飞书/邮件推送,实现问题的早期发现。


实操练习

练习 1:完整故障排查演练

模拟 Gateway 故障并进行排查:

# 第 1 步:查看 Gateway 当前状态
openclaw gateway status
echo "当前状态已记录"

# 第 2 步:检查端口和进程
ps aux | grep openclaw | grep -v grep
lsof -i :18789 2>/dev/null || echo "端口未被占用"

# 第 3 步:验证配置文件完整性
python3 -m json.tool ~/.openclaw/openclaw.json > /dev/null 2>&1 \
  && echo "✅ 配置文件有效" \
  || echo "❌ 配置文件格式错误,尝试恢复备份"

# 第 4 步:运行全面诊断
openclaw doctor

# 第 5 步:查看最近的错误日志
journalctl --user -u openclaw-gateway --priority=err --since "1 hour ago" --no-pager | tail -20

练习 2:编写自定义日志分析脚本

创建一个 Python 脚本,分析 Cron 任务的执行历史:

#!/usr/bin/env python3
# analyze-cron.py — 分析 Cron 任务执行记录
import json, os, glob
from collections import Counter

runs_dir = os.path.expanduser("~/.openclaw/cron/runs/")
status_counter = Counter()

for filepath in glob.glob(os.path.join(runs_dir, "*.jsonl")):
    try:
        with open(filepath) as f:
            lines = f.readlines()
            if lines:
                last = json.loads(lines[-1])
                status = last.get("status", "unknown")
                status_counter[status] += 1
    except Exception as e:
        status_counter["parse_error"] += 1

print("=== Cron 任务执行统计 ===")
for status, count in status_counter.most_common():
    print(f"  {status}: {count} 次")
print(f"  总计: {sum(status_counter.values())} 次")

练习 3:设置磁盘空间监控告警

创建自动清理和告警脚本:

#!/bin/bash
# disk-monitor.sh — 磁盘空间监控
THRESHOLD=80  # 告警阈值百分比

USAGE=$(df -h ~/.openclaw/ | tail -1 | awk '{print $5}' | tr -d '%')
echo "当前磁盘使用率: ${USAGE}%"

if [ "$USAGE" -ge "$THRESHOLD" ]; then
  echo "⚠️  磁盘使用超过 ${THRESHOLD}%,执行清理..."

  # 清理 30 天前的会话
  DELETED=$(find ~/.openclaw/agents/*/sessions/ -mtime +30 -delete -print 2>/dev/null | wc -l)
  echo "已清理 $DELETED 个旧会话文件"

  # 清理 7 天前的 Cron 记录
  DELETED2=$(find ~/.openclaw/cron/runs/ -mtime +7 -delete -print 2>/dev/null | wc -l)
  echo "已清理 $DELETED2 个 Cron 运行记录"

  # 重新检查
  NEW_USAGE=$(df -h ~/.openclaw/ | tail -1 | awk '{print $5}' | tr -d '%')
  echo "清理后磁盘使用率: ${NEW_USAGE}%"
else
  echo "✅ 磁盘空间充足"
fi

常见问题 (FAQ)

Q1: 日志文件存放在哪里?

A: 所有日志在 ~/.openclaw/logs/ 目录下,包含 gateway.log(主日志)、config-audit.jsonl(配置审计)、agent-sessions/(会话日志)。systemd 日志可通过 journalctl --user -u openclaw-gateway 查看。

Q2: 如何重置所有配置回到初始状态?

A: 备份当前配置后删除 ~/.openclaw/openclaw.json,再运行 openclaw onboard 重新初始化。OpenClaw 自动维护 .bak 备份文件,也可用备份快速恢复:

# 查看可用备份
ls -la ~/.openclaw/openclaw.json.bak*

# 使用最新备份恢复
cp ~/.openclaw/openclaw.json.bak ~/.openclaw/openclaw.json
openclaw gateway reload

Q3: Gateway 端口 18789 被其他程序占用了怎么办?

A: 使用 lsof -i :18789 找到占用进程,决定是 kill 该进程还是修改 OpenClaw 端口:

# 方案 1:终止占用进程
kill $(lsof -ti :18789)

# 方案 2:修改 OpenClaw 端口
openclaw config set gateway.port 18790
openclaw gateway restart

Q4: 如何在排查时临时开启 DEBUG 日志又不影响性能?

A: 排查完毕后记得恢复为 info 级别。DEBUG 日志量很大,长时间开启会占用大量磁盘:

# 开启 DEBUG
openclaw config set logLevel debug
# 排查问题...
# 恢复
openclaw config set logLevel info

Q5: Cron 任务连续失败会怎样?

A: OpenClaw 会记录 consecutiveErrors 计数。连续失败超过阈值后会自动暂停该任务,防止资源浪费。可在 jobs.json 中查看状态并手动重置。


外部参考链接


参考来源

来源 链接 可信度 说明
OpenClaw 官方文档 https://docs.OpenClaw.ai A 安装, 配置, 命令
OpenClaw GitHub 仓库 https://github.com/OpenClaw/OpenClaw A 源码, Issues, Release
ClawHub Skills 平台 https://hub.OpenClaw.ai A Skills, 市场, 安装

本章小结

本章系统介绍了 OpenClaw 故障排查与性能优化的完整方法论:

遇到问题时,建议按照「openclaw doctor → 查日志 → 对照故障决策树」的顺序排查。


[← 上一章:单 Gateway 多 Agent 配置与管理](/openclaw-tutorial/08-%E5%8D%95%20Gateway%20%E5%A4%9A%20Agent%20%E9%85%8D%E7%BD%AE%E4%B8%8E%E7%AE%A1%E7%90%86.html) · [📑 返回目录](/openclaw-tutorial/) · [下一章:持续集成与知识库同步 →](/openclaw-tutorial/10-%E6%8C%81%E7%BB%AD%E9%9B%86%E6%88%90%E4%B8%8E%E7%9F%A5%E8%AF%86%E5%BA%93%E5%90%8C%E6%AD%A5.html)