log-analyzer
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseLog Analyzer
日志分析器
Overview
概述
Log viewers filter lines. This skill finds patterns.
Use it when an agent runtime, tool process, gateway, scheduler, or other service
has produced enough log output that individual hits no longer explain the
system behavior. The analyzer parses standard log lines, normalizes repeated
messages, groups errors by component and tool, and produces a structured anomaly
report that is suitable for debugging sessions or cron digests.
grepThe script is intentionally lightweight and portable: it uses only Python's
standard library and works on any text log with timestamp, level, optional
component, and message fields. It also has a best-effort fallback for
unstructured logs.
日志查看器用于过滤行,而本技能用于发现模式。
当Agent运行时、工具进程、网关、调度器或其他服务生成的日志量过大,单独使用已无法解释系统行为时,即可使用本工具。分析器会解析标准日志行,归一化重复消息,按组件和工具分组错误,并生成适合调试会话或Cron摘要的结构化异常报告。
grep本脚本设计轻量且可移植:仅使用Python标准库,适用于包含时间戳、日志级别、可选组件和消息字段的任意文本日志。对于非结构化日志,它也提供了尽力而为的降级处理方案。
Quick Start
快速开始
bash
cd agent-ops/log-analyzer
python scripts/analyze_logs.py scan --log-file agent.log --since 24hTo write JSON for later Markdown rendering:
bash
python scripts/analyze_logs.py scan --log-file agent.log --since 24h --output scan.json
python scripts/analyze_logs.py report --scan scan.json --output report.mdFor cron-compatible anomaly detection:
bash
python scripts/analyze_logs.py scan --log-file agent.log --since 24h --quiet--quietbash
cd agent-ops/log-analyzer
python scripts/analyze_logs.py scan --log-file agent.log --since 24h如需生成JSON以便后续渲染为Markdown:
bash
python scripts/analyze_logs.py scan --log-file agent.log --since 24h --output scan.json
python scripts/analyze_logs.py report --scan scan.json --output report.md用于兼容Cron的异常检测:
bash
python scripts/analyze_logs.py scan --log-file agent.log --since 24h --quiet使用参数时,若未发现异常则以状态码0退出且无输出;若存在异常,则打印JSON报告,以便调度器发送摘要。
--quietWhat It Detects
检测范围
- Error clusters — the same normalized error message repeated 3+ times within the selected time window. URLs, IP addresses, and numbers are replaced with placeholders before grouping so repeated failures with changing IDs still cluster.
- Rate limit hits — HTTP ,
429,rate limit,rate_limit, andtoo many requestspatterns. The analyzer groups them by provider when it can detect a provider name.quota exceeded - Timeout patterns — ,
timeout,timed out, anddeadline exceeded. Results are grouped by detected tool name and include example URLs where present.connection timeout - Tool failures — error lines grouped by tool name extracted from patterns
such as ,
tool: terminal,tool_call: web_search, or lines emitted by atool terminal failedcomponent.tools - Session crashes — fatal errors, unhandled exceptions, stack traces,
,
Traceback, andExceptionmarkers. Multiline stack traces are grouped as one crash entry with nearby context.segfault - Component breakdown — error and warning counts by component such as
,
gateway,agent,tools, orcron.unknown - Error timeline — error counts bucketed by hour to reveal spikes and regressions after deploys or scheduled jobs.
See for detection criteria and interpretation.
references/anomaly-types.md- 错误集群——在选定时间窗口内,同一归一化错误消息重复出现3次及以上。分组前会将URL、IP地址和数字替换为占位符,因此带有变化ID的重复故障仍会被归为一类。
- 速率限制触发——检测HTTP 、
429、rate limit、rate_limit和too many requests等模式。若能识别提供商名称,会按提供商分组。quota exceeded - 超时模式——检测、
timeout、timed out和deadline exceeded等内容。结果按识别出的工具名称分组,包含示例URL(若存在)。connection timeout - 工具故障——从、
tool: terminal、tool_call: web_search等模式或tool terminal failed组件输出的行中提取工具名称,并按工具名称分组错误行。tools - 会话崩溃——检测致命错误、未处理异常、堆栈跟踪、、
Traceback和Exception标记。多行堆栈跟踪会被归为一个崩溃条目,并附带附近上下文。segfault - 组件故障统计——按、
gateway、agent、tools或cron等组件统计错误和警告数量。unknown - 错误时间线——按小时统计错误数量,揭示部署或定时任务后的错误峰值和回归情况。
检测标准和解读方式详见。
references/anomaly-types.mdLog Format Support
日志格式支持
The parser handles standard log lines shaped like:
text
2026-07-06 12:30:45 ERROR [gateway] Connection refused
2026-07-06T12:30:45Z ERROR gateway: Connection refused
12:30:45 ERROR Connection refusedIt recognizes , , , , , , and
levels. Components may appear in square brackets after the level or as
after the level. Time-only lines are anchored to the current day (or
to the supplied default date when called as a library). Unstructured lines fall
back to best-effort line-by-line scanning, so obvious / strings are
still counted even when the timestamp cannot be parsed.
ERRORWARNWARNINGINFODEBUGFATALCRITICALcomponent:ERRORWARNSee for examples and guidance on adding custom
patterns.
references/log-formats.md解析器支持以下格式的标准日志行:
text
2026-07-06 12:30:45 ERROR [gateway] Connection refused
2026-07-06T12:30:45Z ERROR gateway: Connection refused
12:30:45 ERROR Connection refused它能识别、、、、、和等日志级别。组件信息可能出现在级别后的方括号中,或作为形式跟在级别后。仅含时间的日志行默认锚定到当天(作为库调用时可指定默认日期)。非结构化日志行将降级为逐行扫描,因此即使无法解析时间戳,仍会统计明显的/字符串。
ERRORWARNWARNINGINFODEBUGFATALCRITICALcomponent:ERRORWARN添加自定义模式的示例和指导详见。
references/log-formats.mdCLI Commands
CLI命令
scan
— analyze a log file for patterns
scanscan
— 分析日志文件中的模式
scanbash
python scripts/analyze_logs.py scan --log-file LOGFILE [--since TIME] [--output report.json] [--quiet]Options:
- — required path to the log file.
--log-file LOGFILE - — optional time window: minutes/hours/days/weeks, e.g.
--since TIME,30m,1h,24h,7d; default is all lines.2w - — write JSON to a file instead of stdout.
--output report.json - — cron mode: suppress output when no anomalies are found.
--quiet
bash
python scripts/analyze_logs.py scan --log-file LOGFILE [--since TIME] [--output report.json] [--quiet]选项说明:
- — 必填参数,指定日志文件路径。
--log-file LOGFILE - — 可选时间窗口:分钟/小时/天/周,例如
--since TIME、30m、1h、24h、7d;默认分析所有行。2w - — 将JSON写入文件而非输出到标准输出。
--output report.json - — Cron模式:未发现异常时抑制输出。
--quiet
report
— render Markdown from scan JSON
reportreport
— 将扫描结果JSON渲染为Markdown
reportbash
python scripts/analyze_logs.py report --scan scan.json [--output report.md]The report contains overview counts, one section per anomaly type, a component
breakdown table, and an hourly error timeline.
bash
python scripts/analyze_logs.py report --scan scan.json [--output report.md]报告包含概览统计、每种异常类型的单独章节、组件故障统计表和每小时错误时间线。
tail
— smart tail for recent lines
tailtail
— 智能查看最近日志行
tailbash
python scripts/analyze_logs.py tail --log-file LOGFILE [--lines N] [--since TIME]The smart tail prints plain text with markers suitable for chat delivery:
- normal lines: no marker
- warnings:
⚠️ - errors:
❌ - repeated recent errors: when the same normalized error is seen 3+ times
🔥
bash
python scripts/analyze_logs.py tail --log-file LOGFILE [--lines N] [--since TIME]智能查看功能会输出带有适合聊天场景标记的纯文本:
- 正常行:无标记
- 警告:
⚠️ - 错误:
❌ - 近期重复错误:同一归一化错误出现3次及以上时标记为
🔥
Output Format
输出格式
scan- ,
log_file,lines_analyzedtime_window - ,
anomalies.error_clusters,anomalies.rate_limits,anomalies.timeouts,anomalies.tool_failuresanomalies.crashes component_breakdownerror_timeline- ,
total_errors,total_warningshas_anomalies
reportmarkdown
undefinedscan- 、
log_file、lines_analyzedtime_window - 、
anomalies.error_clusters、anomalies.rate_limits、anomalies.timeouts、anomalies.tool_failuresanomalies.crashes component_breakdownerror_timeline- 、
total_errors、total_warningshas_anomalies
reportmarkdown
undefinedLog Analysis Report
日志分析报告
Overview
概述
- Log file: agent.log
- Lines analyzed: 1542
- Time window: 24h
- Total errors: 12 | warnings: 20
- Anomalies detected: 5 types
undefined- 日志文件:agent.log
- 分析行数:1542
- 时间窗口:24h
- 总错误数:12 | 警告数:20
- 检测到的异常类型:5种
undefinedScheduled Summary Integration
定时摘要集成
For a scheduled digest, run in quiet mode and include the output only when
it is non-empty:
scanbash
python scripts/analyze_logs.py scan --log-file /var/log/agent.log --since 24h --quiet --output /tmp/log-scan.json
if [ -s /tmp/log-scan.json ]; then
python scripts/analyze_logs.py report --scan /tmp/log-scan.json
fiA job can append the Markdown output under a "Log anomalies"
heading. Keep the analysis window aligned with the summary window (for example,
24 hours for a daily digest) so counts do not overlap or disappear.
scheduled-summary如需生成定时摘要,可在静默模式下运行,仅当输出非空时才生成报告:
scanbash
python scripts/analyze_logs.py scan --log-file /var/log/agent.log --since 24h --quiet --output /tmp/log-scan.json
if [ -s /tmp/log-scan.json ]; then
python scripts/analyze_logs.py report --scan /tmp/log-scan.json
fischedule-summaryCommon Pitfalls
常见陷阱
- Log rotation breaks time windows. If yesterday's file was rotated out, a
scan over only the current file may miss early-window failures. Point the scheduler at the active file plus rotated file, or concatenate the relevant files before scanning.
--since 24h - Multiline stack traces need the first line. The parser groups indented
stack-trace continuation lines under the preceding parsed log line. If a log
collector strips the first or
Tracebackline, the remaining stack frames become unstructured context.ERROR - Expected errors can be false positives. Retries, probing, and health checks may intentionally emit warnings or connection failures. Treat clusters as "investigate" signals, not automatic incidents.
- First run on a large historical log can overwhelm output. Start with
, inspect the report, then widen the window if needed.
--since 24h - Changing message formats can split clusters. If an application changes an error string during a deploy, pre- and post-deploy failures may appear as two clusters even when the root cause is the same.
- Time-only logs depend on the scan date. lines do not contain a date. For historical files, prefer full timestamps.
12:30:45 ERROR ... - The error timeline buckets by hour-of-day, not date. On a multi-day
window (), errors from 08:00 on different days merge into one
--since 7dbar. Use the clusters (which carry full timestamps) for multi-day forensics; treat the timeline as a time-of-day profile.08:00 - Crash detection is substring-based. The crash regex matches words like
or
fatalanywhere in a line, so mentions inside INFO lines (e.g. "retry succeeded after TimeoutException", "non-fatal warning") count as crash signals and can setException. Treat crash counts as leads to eyeball, and tune the regex if your logs legitimately chat about exceptions at INFO level.has_anomalies
- 日志轮转会破坏时间窗口:如果昨天的日志文件已被轮转,仅对当前文件执行扫描可能会遗漏窗口初期的故障。请将调度器指向活动文件加轮转文件,或在扫描前合并相关文件。
--since 24h - 多行堆栈跟踪需要首行:解析器会将缩进的堆栈跟踪续行归到前一条已解析的日志行下。如果日志收集器剥离了首行或
Traceback,剩余的堆栈帧将成为非结构化上下文。ERROR - 预期错误可能导致误报:重试、探测和健康检查可能会有意输出警告或连接失败信息。请将集群视为“需要调查”的信号,而非自动触发的事件。
- 首次扫描大型历史日志可能输出过载:先使用开始,检查报告后再根据需要扩大窗口。
--since 24h - 消息格式变化会拆分集群:如果应用在部署期间修改了错误字符串,部署前后的故障可能会被分为两个集群,即使根本原因相同。
- 仅含时间的日志依赖扫描日期:格式的行不含日期。对于历史文件,优先使用完整时间戳。
12:30:45 ERROR ... - 错误时间线按一天中的小时分桶,而非日期:在多日窗口(如)下,不同日期08:00的错误会合并到同一个
--since 7d条目中。多日取证请使用带有完整时间戳的集群;时间线仅作为一天中时段的参考。08:00 - 崩溃检测基于子字符串匹配:崩溃正则表达式会匹配行中任意位置的或
fatal等词,因此INFO行中的提及(例如“retry succeeded after TimeoutException”、“non-fatal warning”)也会被视为崩溃信号,并设置Exception。请将崩溃计数作为排查线索,若日志中确实会在INFO级别提及异常,请调整正则表达式。has_anomalies
What This Skill Is NOT
本技能不具备的能力
- Not a log viewer: use ,
tail, or a log UI when you need raw line inspection.less - Not a log shipper: it does not forward logs to storage or observability systems.
- Not a SIEM: it does not correlate identities, networks, or security events.
- Not real-time monitoring: is a recent-line analyzer, not a daemon or alerting service.
tail - Not a root-cause oracle: it highlights patterns so an agent or operator can investigate faster.
- 不是日志查看器:需要查看原始行时,请使用、
tail或日志UI。less - 不是日志转发器:不会将日志转发到存储或可观测性系统。
- 不是SIEM系统:不会关联身份、网络或安全事件。
- 不是实时监控工具:是近期行分析工具,而非守护进程或告警服务。
tail - 不是根因分析预言机:它仅突出显示模式,帮助Agent或运维人员更快开展调查。
Verification Checklist
验证清单
- Run and confirm subcommands load.
python scripts/analyze_logs.py --help - Scan a synthetic log with repeated errors and confirm is true.
has_anomalies - Render Markdown from the scan JSON and confirm all anomaly sections appear.
- Run from this skill directory.
python -m pytest tests/test_analyze_logs.py -v - For cron use, test a no-anomaly log with and confirm stdout is empty with exit code 0.
--quiet
- 运行,确认子命令加载正常。
python scripts/analyze_logs.py --help - 扫描包含重复错误的合成日志,确认为true。
has_anomalies - 将扫描结果JSON渲染为Markdown,确认所有异常章节均已显示。
- 在本技能目录下运行。
python -m pytest tests/test_analyze_logs.py -v - 针对Cron使用场景,测试无异常日志的模式,确认标准输出为空且退出码为0。
--quiet