Monitoring Agent with OpenClaw
A monitoring agent continuously checks your infrastructure, analyses logs for anomalies, verifies API uptime, detects database performance issues, and routes alerts to the right channel — with optional auto-remediation for common failure patterns.
Required Tools
# agents/monitor-agent.yaml
name: monitor-agent
model: gpt-4o-mini
temperature: 0.0
tools:
- shell # run system commands (df, free, ps)
- http_check # HEAD/GET check with latency + status code
- log_reader # tail and parse log files
- notify # send alerts (Slack/PagerDuty/email)
system: |
You are an infrastructure monitoring agent.
Check all requested resources, identify issues, and report clearly.
Use thresholds: CPU > 85% = warning, > 95% = critical.
Disk > 80% = warning, > 90% = critical.
HTTP latency > 2s = warning, > 5s = critical.
Always include a recommended action with every alert.Server Health Check
from openclaw import Agent
agent = Agent.from_config("agents/monitor-agent.yaml")
def server_health_check(host: str) -> dict:
result = agent.run(
f"Check server '{host}':\n"
"1. CPU usage (1-min load average)\n"
"2. RAM usage (used/total, %)\n"
"3. Disk usage for all mounted filesystems\n"
"4. Top 5 processes by CPU\n"
"5. System uptime\n"
"Return JSON with a 'status' field: 'ok' | 'warning' | 'critical', "
"and a 'summary' string."
)
import json
return json.loads(result)Log Analysis and Anomaly Detection
def analyse_logs(log_path: str, lines: int = 500) -> str:
return agent.run(
f"Read the last {lines} lines of '{log_path}'. Identify:\n"
"1. Error rate (errors per 100 lines)\n"
"2. Any repeated error patterns (top 5 by frequency)\n"
"3. Any spike in errors vs. earlier log sections\n"
"4. Specific exceptions or stack traces worth investigating\n"
"Summarise in plain English with severity: ok/warning/critical."
)API Uptime Monitoring
import time, datetime
ENDPOINTS = [
{"name": "API Gateway", "url": "https://api.example.com/health"},
{"name": "Auth Service", "url": "https://auth.example.com/ping"},
{"name": "CDN", "url": "https://cdn.example.com/"},
]
def check_all_endpoints() -> list[dict]:
results = []
for ep in ENDPOINTS:
result = agent.run(
f"HTTP check '{ep['url']}'. Return JSON: "
"{\"name\": \"\", \"url\": \"\", \"status_code\": 0, "
"\"latency_ms\": 0, \"status\": \"ok|warning|critical\"}"
)
import json
results.append(json.loads(result))
return resultsAlert Routing
import os, requests
SLACK_WEBHOOK = os.environ["SLACK_WEBHOOK_URL"]
def send_alert(message: str, severity: str = "warning") -> None:
"""Route alert to Slack with colour-coded severity."""
colour = {"ok": "#22c55e", "warning": "#eab308", "critical": "#ef4444"}.get(severity, "#9898b8")
payload = {
"attachments": [{
"color": colour,
"text": message,
"footer": f"OpenClaw Monitor | {severity.upper()}",
}]
}
requests.post(SLACK_WEBHOOK, json=payload, timeout=5)
def run_monitoring_cycle() -> None:
"""Single monitoring pass — call from cron every 5 minutes."""
for ep_result in check_all_endpoints():
if ep_result["status"] != "ok":
send_alert(
f"{ep_result['name']}: {ep_result['status_code']} "
f"({ep_result['latency_ms']}ms) — {ep_result['url']}",
severity=ep_result["status"],
)Scheduling with Cron
# Run a full health check every 5 minutes
*/5 * * * * /usr/bin/python3 /opt/openclaw/monitor.py >> /var/log/openclaw-monitor.log 2>&1
# Daily log anomaly report at 07:00
0 7 * * * /usr/bin/python3 /opt/openclaw/log_report.py --output=/reports/ >> /var/log/openclaw-monitor.log 2>&1Frequently Asked Questions
How do I prevent alert fatigue from a monitoring agent?
Implement intelligent thresholding: don't alert on every anomaly, only deviations >2 standard deviations from baseline. Use rate limiting: max 1 alert per metric per hour. Group related alerts into a single notification (e.g., "3 services down" instead of 3 separate messages). Add a snooze_alert(metric, duration) function for maintenance windows. For non-critical metrics, batch alerts into daily digest emails rather than instant notifications.
Can the agent auto-remediate issues?
Yes, but with safeguards. For safe actions (restart a crashed service, clear a cache), allow automatic execution. For risky operations (database migrations, firewall changes), require human approval before executing. Use an approval queue: agent proposes a fix, posts to Slack with "Approve/Reject" buttons, and waits for confirmation. Always log all remediation actions in an audit trail with timestamps and outcomes.
Which monitoring APIs integrate well with OpenClaw?
Prometheus (metrics + alertmanager), Grafana (dashboards + alerts), Datadog (full-stack APM), New Relic (application monitoring), PagerDuty (incident management), Sentry (error tracking). All provide REST APIs for querying metrics and posting annotations. Start with Prometheus if self-hosting; use Datadog for SaaS simplicity.
How often should monitoring agents run checks?
For critical metrics (API uptime, database connections): every 1–5 minutes. For performance indicators (CPU, memory): every 5–10 minutes. For business metrics (daily revenue, user signups): hourly or daily. Avoid sub-minute polling (generates noise); use push-based monitoring (Prometheus Pushgateway) for event-driven checks instead of cron-based intervals.