Skills 日志、运行指标与步骤追踪
用运行标识连接事件,按明确分母计算指标,结合实际步骤用时定位故障。
学完这一章,你能够
- 用运行标识连接事件,按明确分母计算指标,结合实际步骤用时定位故障。
同一运行用同一标识串起各阶段
日志说明实际发生什么,指标反映一批任务的表现,追踪解释一项任务经过哪些步骤。为一次运行分配标识,再登记 UTC 时间、级别、事件名、递增序号和必要字段。本站每次运行写独立的 UTF-8 JSONL,同时把事件发到 stderr,stdout 返回单个业务对象。
日志里保留步骤、状态与计时,数据内容、完整路径和令牌留在各自的授权范围。示例保留每次真实运算的数量;部署时另确定采样、保留和故障记录口径。
先定义分母再比较成功率
从日志行解析事件,按运行 ID 与事件序号归并。同一事件重复写入只算一次,不同内容使用同一序号会列为冲突。缺终止记录、孤立结束、冲突和格式错误分别登记。计算已结束运行的成功率时用成功次数加失败次数作分母,无已结束运行时返回 null。
一次失败可有多条错误事件。用有效终止记录确定每次运行结果,另外统计错误事件和最近的失败终止。平均成功耗时按成功运行的实际计时计算,明确单位。
追踪真实步骤并保存结果
用共享运行标识记录读取、规范化和汇总。步骤用时由 perf_counter_ns 的差值获得,事件时间和测量用时各有用途。失败步骤也要记录自己的用时和状态。
本地运行通过两个成功和一个数据错误得到 JSON 报告,并继续复核缺结束、冲突及无效条目。跨主机链路串联、长期存储和告警需要目标运行环境支持。
三种观察方式
| 条目 | 用途与条件 |
|---|---|
| 运行事件 | 保留结构化时间、步骤与诊断。 |
| 聚合口径 | 按运行统计结果,错误日志数单独保存。 |
| 步骤观察 | 按同一运行标识恢复阶段、耗时和结果。 |
用实际运行日志生成指标并回读步骤
"""Record local stock runs and compute metrics by run identity."""
import argparse
from collections import Counter, defaultdict
from contextlib import contextmanager
import csv
from datetime import datetime, timezone
import json
from pathlib import Path
import sys
from time import perf_counter_ns
from uuid import uuid4
EVENTS={"run_start","step_start","step_finish","run_finish"}
class Trace:
def __init__(self, directory):
self.run=uuid4().hex
self.directory=directory
self.started=perf_counter_ns()
self.sequence=0
self.channel=directory/(self.run+".jsonl")
def event(self, name, level="info", **details):
self.sequence+=1
row={"run":self.run,"event":name,"level":level,"sequence":self.sequence,
"ts":datetime.now(timezone.utc).isoformat(),**details}
serialized=json.dumps(row,ensure_ascii=False,separators=(",",":"))
with self.channel.open("a",encoding="utf-8",newline="\n") as log:
log.write(serialized+"\n")
print(serialized,file=sys.stderr)
@contextmanager
def step(self,name):
self.event("step_start",step=name)
started=perf_counter_ns()
try:
yield
except (OSError,ValueError,csv.Error):
self.event("step_finish","error",step=name,status="failed",elapsed_ns=perf_counter_ns()-started)
raise
else:
self.event("step_finish",step=name,status="ok",elapsed_ns=perf_counter_ns()-started)
def run_stock(source,directory):
directory.mkdir(parents=True,exist_ok=True)
trace=Trace(directory)
trace.event("run_start")
try:
with trace.step("read"):
with source.open(encoding="utf-8",newline="") as file:
reader=csv.DictReader(file,strict=True)
if reader.fieldnames!=["zone","units"]:
raise ValueError("columns")
rows=list(reader)
with trace.step("normalize"):
values=[int(row["units"]) for row in rows if row["units"]]
with trace.step("total"):
total=sum(values)
except (OSError,ValueError,csv.Error) as error:
trace.event("run_finish","error",status="failed",code=type(error).__name__,
elapsed_ns=perf_counter_ns()-trace.started)
return 2,{"ok":False,"run":trace.run,"code":type(error).__name__}
trace.event("run_finish",status="ok",elapsed_ns=perf_counter_ns()-trace.started)
return 0,{"ok":True,"run":trace.run,"rows":len(rows),"units":total}
def parse_event(line):
event=json.loads(line)
if (not isinstance(event,dict) or not isinstance(event.get("run"),str) or
type(event.get("sequence")) is not int or event["sequence"]<1 or
event.get("event") not in EVENTS or event.get("level") not in ("info","warning","error") or
datetime.fromisoformat(event["ts"]).utcoffset() is None):
raise ValueError("event schema")
if event["event"].startswith("step") and not isinstance(event.get("step"),str):
raise ValueError("step")
if event["event"].endswith("finish") and (
type(event.get("elapsed_ns")) is not int or event["elapsed_ns"]<0 or event.get("status") not in ("ok","failed")):
raise ValueError("finish schema")
return event
def aggregate(directory):
by_run=defaultdict(dict)
invalid=set()
counts=Counter()
for log in directory.glob("*.jsonl"):
for line in log.read_bytes().splitlines():
if not line.strip():
continue
try:
event=parse_event(line)
except (ValueError,KeyError,TypeError):
counts["malformed"]+=1
continue
run=event["run"]
seq=event["sequence"]
original=by_run[run].setdefault(seq,event)
if original!=event:
invalid.add(run)
recent=[]
times=[]
traces={}
for run,group in by_run.items():
events=[group[key] for key in sorted(group)]
counts["error_events"]+=sum(item["level"]=="error" for item in events)
if run in invalid:
counts["conflict"]+=1
continue
starts=[e for e in events if e["event"]=="run_start"]
finishes=[e for e in events if e["event"]=="run_finish"]
if not starts:
counts["orphan"]+=1
continue
counts["started"]+=1
if len(starts)!=1 or len(finishes)>1 or events[0]!=starts[0] or (finishes and events[-1]!=finishes[0]):
counts["conflict"]+=1
continue
traces[run]=[{"step":e["step"],"status":e["status"],"elapsed_ns":e["elapsed_ns"]} for e in events if e["event"]=="step_finish"]
if not finishes:
counts["incomplete"]+=1
elif finishes[0]["status"]=="ok":
counts["success"]+=1
times.append(finishes[0]["elapsed_ns"])
else:
counts["failure"]+=1
recent.append({k:finishes[0].get(k) for k in ("ts","run","code")})
completed=counts["success"]+counts["failure"]
return {"metrics":{k:counts[k] for k in ("started","success","failure","incomplete","orphan","conflict",
"malformed","error_events")},"success_rate_among_completed":counts["success"]/completed if completed else None,
"average_success_ns":sum(times)/len(times) if times else None,
"recent_errors":sorted(recent,key=lambda item:datetime.fromisoformat(item["ts"]))[-5:],"traces":traces}
def main():
parser=argparse.ArgumentParser(description=__doc__)
commands=parser.add_subparsers(dest="command",required=True)
run=commands.add_parser("run")
run.add_argument("source",type=Path)
run.add_argument("log_dir",type=Path)
report=commands.add_parser("metrics")
report.add_argument("log_dir",type=Path)
args=parser.parse_args()
if args.command=="run":
code,result=run_stock(args.source,args.log_dir)
elif not args.log_dir.is_dir():
code,result=2,{"ok":False,"code":"MISSING_LOG_DIRECTORY"}
else:
code,result=0,aggregate(args.log_dir)
print(json.dumps(result,ensure_ascii=False))
return code
if __name__=="__main__":
raise SystemExit(main())
- 运行本地库存统计并生成按运行区分的 JSONL。两次成功和一次失败得到按已结束运行计算的 2/3;步骤失败日志和该次运行结束日志增加诊断事件数,各只归到同一次失败运行。
所需环境:Windows、Python 3.12。各实验所需工具和版本见下载包 README。
当前源码 SHA256:3183bf97376e9436a6405ca6d4b08504bac12effc9a3256a5d28897869ddafd6
运行本地实验
解压后按 README 运行当前章节对应的脚本,并查看真实输出。
所需环境:Windows、Python 3.12。各实验所需工具和版本见下载包 README。
ZIP SHA256:5efc9af6fc5d76ea044fde4e315d16c53b4c4e1135e6b1f972bab80cb3e894c4
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
一次任务产出三条错误日志,失败次数该如何统计?
展开参考解答
用运行 ID 及终止状态计算失败任务数,把错误事件数另外记录。