返回

07. OpenClaw 运行时问题排查完全指南

详细排查 OpenClaw 运行时问题,包括 Gateway 崩溃、会话异常、Agent 无响应、数据丢失等。提供监控告警和故障恢复方案。

适用于 OpenClaw v2026.2 | 本文适合遇到运行时故障的用户。

TL;DR: 查看进程:ps aux | grep openclaw。查看日志:openclaw logs --tail 100。重启服务:openclaw gateway --restart。重置会话:openclaw session reset main。数据备份:tar -czvf openclaw-backup.tar.gz ~/.openclaw。监控配置:openclaw config set monitoring.enabled true

常见问题速查表

问题 症状 快速解决
Gateway 崩溃 进程消失 查看日志、重启服务
会话异常 无法对话或数据错误 重置会话、清理缓存
Agent 无响应 长时间无输出 检查网络、API 配额
内存泄漏 内存持续增长 重启、检查日志
数据丢失 配置或会话消失 从备份恢复
CPU 100% 系统卡死 检查死循环、限制并发

问题 1:Gateway 崩溃

症状

$ openclaw gateway
# 程序突然退出,无输出

$ ps aux | grep openclaw
# 无进程

诊断方法

# 1. 查看系统日志
journalctl -u openclaw -n 50 --no-pager

# 2. 查看 OpenClaw 日志
tail -100 ~/.openclaw/logs/gateway.log

# 3. 检查崩溃转储(如果启用)
ls -la ~/.openclaw/crashes/

# 4. 使用调试模式运行
openclaw gateway --verbose --debug

# 5. 检查系统资源
dmesg | tail -50

常见原因和解决方案

原因 1:内存不足

# 症状
Error: JavaScript heap out of memory
# 或系统日志显示:Out of memory: Kill process

# 解决方案
# 增加内存限制
export NODE_OPTIONS="--max-old-space-size=8192"
openclaw gateway

# 或在 Docker 中
docker run -e NODE_OPTIONS="--max-old-space-size=8192" \
  --memory="4g" openclaw/openclaw:latest

原因 2:未捕获的异常

# 症状
TypeError: Cannot read property 'x' of undefined

# 解决方案
# 1. 查看完整错误栈
openclaw logs --tail 200 | grep -A 20 "Error"

# 2. 更新到最新版本
openclaw update

# 3. 报告 Bug
# 访问 https://github.com/openclaw/openclaw/issues
# 提交完整的错误信息和复现步骤

# 4. 临时回退版本
npm install -g [email protected]

原因 3:依赖损坏

# 症状
Error: Cannot find module 'xxx'

# 解决方案
# 1. 重新安装依赖
cd /usr/local/lib/node_modules/openclaw
npm install

# 或重新安装 OpenClaw
npm uninstall -g openclaw
npm install -g openclaw@latest

# 2. 清理缓存
npm cache clean --force

原因 4:端口冲突

# 症状
Error: EADDRINUSE: address already in use :::18789

# 解决方案
# 查找占用进程
lsof -i :18789

# 终止进程
kill -9 <PID>

# 或使用其他端口
openclaw gateway --port 18790

自动重启配置

使用 systemd

创建 /etc/systemd/system/openclaw.service

[Unit]
Description=OpenClaw Gateway
After=network.target

[Service]
Type=simple
User=your-username
WorkingDirectory=/home/your-username
Environment="NODE_OPTIONS=--max-old-space-size=8192"
Environment="ANTHROPIC_API_KEY=your-key"
ExecStart=/usr/local/bin/openclaw gateway
Restart=always
RestartSec=10
StandardOutput=append:/home/your-username/.openclaw/logs/gateway.log
StandardError=append:/home/your-username/.openclaw/logs/gateway.log

[Install]
WantedBy=multi-user.target

启用服务:

sudo systemctl daemon-reload
sudo systemctl enable openclaw
sudo systemctl start openclaw

# 查看状态
sudo systemctl status openclaw

# 查看日志
sudo journalctl -u openclaw -f

使用 PM2

# 安装 PM2
npm install -g pm2

# 启动 OpenClaw
pm2 start openclaw --name "openclaw" -- gateway

# 开机自启
pm2 startup
pm2 save

# 查看状态
pm2 status

# 查看日志
pm2 logs openclaw

# 重启
pm2 restart openclaw

使用 Docker

# docker-compose.yml
version: '3.8'
services:
  openclaw:
    image: openclaw/openclaw:latest
    container_name: openclaw
    restart: always
    ports:
      - "18789:18789"
    volumes:
      - ./openclaw-data:/root/.openclaw
    environment:
      - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
      - NODE_OPTIONS=--max-old-space-size=8192

问题 2:会话异常

症状 1:会话无法加载

Error: Failed to load session 'main': Unexpected token < in JSON

解决方案

# 1. 检查会话文件
ls -la ~/.openclaw/sessions/

# 2. 查看会话文件内容
cat ~/.openclaw/sessions/main.json | head -50

# 3. 验证 JSON 格式
cat ~/.openclaw/sessions/main.json | jq .

# 4. 如果文件损坏,重置会话
openclaw session reset main

# 5. 从备份恢复
cp ~/.openclaw/sessions/main.json.backup ~/.openclaw/sessions/main.json

症状 2:会话数据丢失

$ openclaw session list
Session 'main' not found

解决方案

# 1. 检查会话目录
ls -la ~/.openclaw/sessions/

# 2. 从备份恢复
# 如果有备份
tar -xzvf openclaw-backup-20260306.tar.gz -C ~/ \
  .openclaw/sessions/main.json

# 3. 重新创建会话
openclaw session create main

# 4. 检查是否启用了会话持久化
openclaw config get session.persistence.enabled

症状 3:会话过大

Warning: Session 'main' is large (150MB), performance may be affected

解决方案

# 1. 查看会话大小
openclaw session list --with-size

# 2. 压缩会话
openclaw session compress main

# 3. 或重置会话
openclaw session reset main

# 4. 配置自动压缩
openclaw config set session.autoCompress true
openclaw config set session.maxTokens 50000

# 5. 配置历史限制
openclaw config set session.historyLimit 100

症状 4:会话锁定

Error: Session 'main' is locked by another process

解决方案

# 1. 查看锁定进程
openclaw session show main --lock-info

# 2. 强制解锁
openclaw session unlock main --force

# 3. 检查是否有其他 Gateway 实例
ps aux | grep openclaw

# 4. 终止其他实例
pkill -9 openclaw

# 5. 重启 Gateway
openclaw gateway

问题 3:Agent 无响应

症状

$ openclaw agent --message "你好"
# 长时间等待,无输出

诊断方法

# 1. 检查 Gateway 状态
openclaw doctor

# 2. 检查网络连接
curl -I https://api.anthropic.com

# 3. 查看日志
openclaw logs --tail 50 --follow

# 4. 测试 API
time openclaw agent --message "hi" --timeout 5000

# 5. 检查 API 配额
openclaw usage --api-status

常见原因和解决方案

原因 1:API 配额耗尽

# 症状
Error: Rate limit exceeded. Please retry after 60 seconds.

# 解决方案
# 1. 查看配额使用
openclaw usage --today

# 2. 等待配额恢复
sleep 60

# 3. 配置备用模型
openclaw config set models.fallback '[
  {"model": "anthropic/claude-sonnet-4", "condition": "rate_limit"},
  {"model": "openai/gpt-4o-mini", "condition": "rate_limit"}
]'

# 4. 设置重试策略
openclaw config set api.retry.enabled true
openclaw config set api.retry.maxAttempts 5

原因 2:网络超时

# 症状
Error: ETIMEDOUT

# 解决方案
# 1. 增加超时时间
openclaw config set network.timeout 60000

# 2. 使用代理
export HTTPS_PROXY=http://127.0.0.1:7890

# 3. 检查网络稳定性
ping -c 10 api.anthropic.com

# 4. 使用 CDN 或更近的端点

原因 3:任务过于复杂

# 症状
# 长时间处理,但无错误

# 解决方案
# 1. 简化任务
openclaw agent --message "列出当前目录的文件" --timeout 30000

# 2. 使用更快的模型
openclaw agent --message "..." --model claude-haiku-3.5

# 3. 分步执行复杂任务
# 在对话中分步指导

# 4. 启用流式响应
openclaw config set agent.streaming.enabled true

原因 4:工具卡死

# 症状
# Agent 在执行工具时卡住

# 解决方案
# 1. 查看工具执行状态
openclaw logs --grep "tool.invoke" --tail 20

# 2. 配置工具超时
openclaw config set tools.timeout 30000

# 3. 禁用问题工具
openclaw config set tools.disabled '["problematic-tool"]'

# 4. 重启 Gateway
openclaw gateway --restart

问题 4:内存泄漏

症状

# 内存使用持续增长
$ top -p $(pgrep -f openclaw)
# 内存从 500MB 增长到 2GB+

# 日志显示
Warning: Memory usage high: 90%

诊断方法

# 1. 监控内存使用
watch -n 5 'ps aux | grep openclaw | grep -v grep | awk "{print \$6/1024\" MB\"}"'

# 2. 生成内存快照
kill -USR2 $(pgrep -f openclaw)
# 快照保存在 ~/.openclaw/heapdump/

# 3. 分析内存分布
openclaw diagnostics memory

# 4. 检查会话和缓存
openclaw session list --with-size
openclaw cache stats

解决方案

方案 1:定期重启

# 使用 cron 定期重启
crontab -e

# 每天凌晨 4 点重启
0 4 * * * /usr/local/bin/openclaw gateway --restart

方案 2:限制内存使用

# 设置内存限制
openclaw config set limits.memory "4GB"

# 启用内存监控
openclaw config set monitoring.memory.enabled true
openclaw config set monitoring.memory.threshold 0.9

方案 3:清理缓存

# 定期清理缓存
openclaw cache clear --older-than 1d

# 配置自动清理
openclaw config set cache.autoClear.enabled true
openclaw config set cache.autoClear.interval 86400

方案 4:优化配置

{
  "session": {
    "autoCompress": true,
    "maxTokens": 30000,
    "cleanup": {
      "enabled": true,
      "maxAge": 604800
    }
  },
  "cache": {
    "enabled": true,
    "maxSize": "200MB",
    "ttl": 3600
  },
  "logging": {
    "level": "warn",
    "rotation": {
      "enabled": true,
      "maxSize": "50MB"
    }
  }
}

问题 5:数据丢失

症状 1:配置丢失

$ openclaw config get
Error: Configuration file not found

解决方案

# 1. 检查备份
ls -la ~/.openclaw/*.backup
ls -la ~/.openclaw/openclaw.json.*

# 2. 恢复备份
cp ~/.openclaw/openclaw.json.backup ~/.openclaw/openclaw.json

# 3. 如果没有备份,重新配置
openclaw onboard

# 4. 启用自动备份
openclaw config set backup.enabled true
openclaw config set backup.interval 3600

症状 2:会话数据丢失

已在问题 2 中讨论。

症状 3:凭据丢失

Error: Telegram credentials not found

解决方案

# 1. 检查凭据目录
ls -la ~/.openclaw/credentials/

# 2. 重新登录
openclaw channels login telegram

# 3. 从备份恢复
# 如果有加密备份
openclaw credentials import --input credentials.enc

# 4. 启用凭据备份
openclaw config set credentials.backup.enabled true

预防措施

定期备份

创建备份脚本 backup-openclaw.sh

#!/bin/bash

BACKUP_DIR=~/backups/openclaw
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="openclaw-backup-$DATE.tar.gz"

mkdir -p $BACKUP_DIR

# 备份关键数据
tar -czvf $BACKUP_DIR/$BACKUP_FILE \
  ~/.openclaw/openclaw.json \
  ~/.openclaw/workspace/AGENTS.md \
  ~/.openclaw/workspace/SOUL.md \
  ~/.openclaw/workspace/USER.md \
  ~/.openclaw/credentials/ \
  ~/.openclaw/sessions/

# 保留最近 7 天的备份
find $BACKUP_DIR -name "openclaw-backup-*.tar.gz" -mtime +7 -delete

echo "Backup created: $BACKUP_DIR/$BACKUP_FILE"

配置 cron:

# 每天凌晨 2 点备份
0 2 * * * /path/to/backup-openclaw.sh >> ~/backups/openclaw/backup.log 2>&1

云存储同步

# 使用 rsync 同步到远程服务器
rsync -avz ~/.openclaw/ user@backup-server:~/openclaw-backup/

# 或使用 rclone 同步到云存储
rclone sync ~/.openclaw/ remote:openclaw-backup/

问题 6:CPU 100%

症状

$ top -p $(pgrep -f openclaw)
# CPU 使用率 100%

诊断方法

# 1. 查看线程 CPU 使用
top -H -p $(pgrep -f openclaw)

# 2. 使用 perf 分析
sudo perf top -p $(pgrep -f openclaw)

# 3. 生成 CPU Profile
kill -USR1 $(pgrep -f openclaw)
# Profile 保存在 ~/.openclaw/cpuprofile/

# 4. 查看运行任务
openclaw status --tasks

解决方案

原因 1:死循环

# 检查日志中的循环
openclaw logs --tail 100 | grep -E "(loop|repeat|stuck)"

# 重启 Gateway
openclaw gateway --restart

# 报告 Bug
# 提交完整的日志和复现步骤

原因 2:过多并发

# 查看当前并发
openclaw status --concurrency

# 限制并发
openclaw config set performance.maxConcurrency 5

原因 3:复杂计算

# 查看执行中的任务
openclaw tasks list --running

# 取消长时间运行的任务
openclaw tasks cancel <task-id>

# 限制任务超时
openclaw config set tasks.timeout 60000

监控和告警

健康检查

创建健康检查脚本 health-check.sh

#!/bin/bash

# 检查 Gateway 是否运行
if ! pgrep -f "openclaw gateway" > /dev/null; then
    echo "❌ Gateway not running"
    # 尝试重启
    openclaw gateway --daemon
    exit 1
fi

# 检查端口
if ! lsof -i :18789 > /dev/null 2>&1; then
    echo "❌ Port 18789 not listening"
    openclaw gateway --restart
    exit 1
fi

# 检查内存使用
MEM_USAGE=$(ps aux | grep "openclaw gateway" | grep -v grep | awk '{print $4}' | head -1)
MEM_INT=${MEM_USAGE%.*}

if [ "$MEM_INT" -gt 90 ]; then
    echo "⚠️  High memory usage: ${MEM_USAGE}%"
    # 可选:自动重启
    # openclaw gateway --restart
fi

# 检查磁盘空间
DISK_USAGE=$(df -h ~/.openclaw | tail -1 | awk '{print $5}' | sed 's/%//')

if [ "$DISK_USAGE" -gt 90 ]; then
    echo "⚠️  High disk usage: ${DISK_USAGE}%"
    # 清理日志
    find ~/.openclaw/logs -name "*.log" -mtime +7 -delete
fi

# 检查日志错误
ERROR_COUNT=$(grep -c "Error" ~/.openclaw/logs/gateway.log 2>/dev/null || echo "0")

if [ "$ERROR_COUNT" -gt 10 ]; then
    echo "⚠️  High error count in logs: $ERROR_COUNT"
fi

echo "✅ Health check passed"

配置 cron 定期检查:

# 每 5 分钟检查一次
*/5 * * * * /path/to/health-check.sh >> ~/.openclaw/logs/health.log 2>&1

告警配置

{
  "monitoring": {
    "enabled": true,
    "alerts": {
      "memory": {
        "threshold": 90,
        "action": ["log", "notify", "restart"]
      },
      "cpu": {
        "threshold": 85,
        "duration": 300,
        "action": ["log", "notify"]
      },
      "disk": {
        "threshold": 90,
        "action": ["log", "notify", "cleanup"]
      },
      "errorRate": {
        "threshold": 0.05,
        "action": ["log", "notify"]
      },
      "responseTime": {
        "threshold": 10000,
        "action": ["log", "notify"]
      }
    },
    "notifications": {
      "email": "[email protected]",
      "webhook": "https://hooks.slack.com/services/xxx",
      "discord": "https://discord.com/api/webhooks/xxx"
    }
  }
}

故障恢复流程

快速恢复清单

  1. 检查进程

    ps aux | grep openclaw
    
  2. 查看日志

    openclaw logs --tail 100
    
  3. 重启服务

    openclaw gateway --restart
    
  4. 验证状态

    openclaw doctor
    
  5. 测试功能

    openclaw agent --message "test"
    

完整恢复流程

#!/bin/bash

echo "=== OpenClaw 故障恢复 ==="

# 1. 停止所有进程
echo "停止服务..."
pkill -9 openclaw
sleep 2

# 2. 清理临时文件
echo "清理临时文件..."
rm -rf /tmp/openclaw-*
rm -rf ~/.openclaw/tmp/*

# 3. 检查配置
echo "验证配置..."
if [ ! -f ~/.openclaw/openclaw.json ]; then
    echo "❌ 配置文件丢失,尝试恢复备份..."
    if [ -f ~/.openclaw/openclaw.json.backup ]; then
        cp ~/.openclaw/openclaw.json.backup ~/.openclaw/openclaw.json
        echo "✅ 配置已恢复"
    else
        echo "❌ 无备份,需要重新配置"
        exit 1
    fi
fi

# 4. 验证 API Key
echo "验证 API Key..."
if [ -z "$ANTHROPIC_API_KEY" ] && [ -z "$OPENAI_API_KEY" ]; then
    echo "⚠️  未配置 API Key"
fi

# 5. 重置异常会话
echo "检查会话..."
for session in ~/.openclaw/sessions/*.json; do
    if ! jq empty "$session" 2>/dev/null; then
        echo "❌ 损坏的会话: $session"
        rm "$session"
    fi
done

# 6. 清理缓存
echo "清理缓存..."
openclaw cache clear

# 7. 启动服务
echo "启动服务..."
openclaw gateway --daemon

# 8. 等待启动
sleep 5

# 9. 验证
echo "验证状态..."
if openclaw doctor; then
    echo "✅ 恢复成功"
else
    echo "❌ 恢复失败,请检查日志"
    exit 1
fi

echo "=== 恢复完成 ==="

小结

运行时问题是生产环境中的常见挑战:

  1. Gateway 崩溃:配置自动重启、监控日志
  2. 会话异常:定期备份、验证数据、限制大小
  3. Agent 无响应:检查网络、API、任务复杂度
  4. 内存泄漏:监控内存、定期重启、优化配置
  5. 数据丢失:定期备份、云存储同步
  6. CPU 100%:限制并发、检查死循环、优化任务

运维的核心原则:

  • 监控优先:实时监控系统健康
  • 自动恢复:配置自动重启和告警
  • 定期备份:保护关键数据
  • 文档记录:记录问题和解决方案

系列总结

恭喜你完成了 OpenClaw 问题排查系列!7 篇文章涵盖了:

  1. 安装部署问题 - Node.js、依赖、Docker、权限
  2. 配置问题 - 配置文件、API Key、环境变量
  3. 连接问题 - 渠道、网络、WebSocket
  4. 性能问题 - 内存、CPU、响应速度
  5. 安全问题 - 访问控制、权限、数据保护
  6. Skills 问题 - 安装、执行、开发
  7. 运行时问题 - 崩溃、会话、监控

遇到问题时,记住:

  • 先运行 openclaw doctor 诊断
  • 查看日志定位问题
  • 参考对应文章的解决方案
  • 在社区寻求帮助

更新记录

  • 2026-03-06:初版发布,涵盖 6 大类运行时问题

系列导航