78 lines
3.7 KiB
Python
78 lines
3.7 KiB
Python
"""Full engineering traces, independent of public events and JSON stdout transport."""
|
|
import functools
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import sys
|
|
import threading
|
|
import time
|
|
from datetime import datetime
|
|
from zoneinfo import ZoneInfo
|
|
|
|
_root=None
|
|
_task='startup'
|
|
_lock=threading.Lock()
|
|
_SECRET=re.compile(r'^(?:api[-_]?key|authorization|access[-_]?token|refresh[-_]?token|id[-_]?token|password|secret|cookie|client[-_]?secret)$',re.I)
|
|
|
|
def configure(root):
|
|
global _root
|
|
_root=Path(root)
|
|
|
|
def task(tid):
|
|
global _task
|
|
if re.fullmatch(r'[a-z0-9_-]{1,80}',str(tid)):_task=str(tid)
|
|
|
|
def redact(value):
|
|
if isinstance(value,dict):return {str(k):'[认证信息已隐藏]' if _SECRET.fullmatch(str(k)) else redact(v) for k,v in value.items()}
|
|
if isinstance(value,(tuple,list)):return [redact(v) for v in value]
|
|
if isinstance(value,bytes):return {'binary_bytes':len(value)}
|
|
if not isinstance(value,str):return value
|
|
value=re.sub(r'(?i)(bearer\s+)\S+',r'\1[认证信息已隐藏]',value)
|
|
value=re.sub(r'\bsk-[A-Za-z0-9_-]+','[认证信息已隐藏]',value)
|
|
value=re.sub(r'(?i)((?:api[_-]?key|access_token|refresh_token|password|secret)\s*[=:]\s*)[^\s,;]+',r'\1[认证信息已隐藏]',value)
|
|
value=re.sub(r'data:[^;\s]+;base64,[A-Za-z0-9+/=]+','[二进制附件省略]',value)
|
|
for k,v in os.environ.items():
|
|
if len(v)>=8 and (k.endswith(('_API_KEY','_TOKEN','_PASSWORD','_SECRET')) or k=='OPENAI_API_KEY'):
|
|
value=value.replace(v,'[认证信息已隐藏]')
|
|
return re.sub(r'[\x00-\x08\x0b-\x1f\x7f-\x9f]',' ',value)
|
|
|
|
def log(title,data):
|
|
if _root is None or os.getenv('AI_PCB_DEV_LOG','1')=='0':return
|
|
try:
|
|
title={'AI request':'向 AI 提问:完整指令、上下文和输出约束',
|
|
'AI response':'AI 回答:模型返回的完整结果',
|
|
'AI failed':'AI 调用失败:诊断详情',
|
|
'EDA action plan':'准备执行 EDA 动作:操作说明、脚本和检查依据',
|
|
'EDA Bridge request':'向 EDA 桥接提交脚本',
|
|
'EDA Bridge response':'EDA 桥接返回执行结果'}.get(title,title)
|
|
if title.startswith('Engineering event: '):title='工程事件详情:'+title.split(': ',1)[1]
|
|
stamp=datetime.now(ZoneInfo('Asia/Shanghai')).strftime('%Y-%m-%d %H:%M:%S')
|
|
header=f'[{stamp} +08:00] [{_task}] [开发详情] '
|
|
body=json.dumps(redact(data),ensure_ascii=False,indent=2,default=str)
|
|
block=header+title+'\n'+''.join(header+line+'\n' for line in body.splitlines())+header+'详情结束\n'
|
|
with _lock:
|
|
directory=_root/'logs'/'debug';directory.mkdir(parents=True,exist_ok=True)
|
|
with (directory/(_task+'.log')).open('a',encoding='utf-8') as stream:stream.write(block)
|
|
try:sys.stderr.write(block);sys.stderr.flush()
|
|
except (OSError,ValueError):pass
|
|
except Exception:pass
|
|
|
|
def traced(title):
|
|
def decorate(fn):
|
|
@functools.wraps(fn)
|
|
def wrapped(*args,**kwargs):
|
|
# CLI has executable, command and optional script stdin. Never log a process environment.
|
|
log(title+':提交',{'command':args[1] if len(args)>1 else kwargs.get('args'),
|
|
'script_stdin':kwargs.get('input_text')})
|
|
started=time.monotonic()
|
|
try:
|
|
value=fn(*args,**kwargs)
|
|
except Exception as exc:
|
|
log(title+':失败',{'seconds':round(time.monotonic()-started,3),'type':type(exc).__name__,'error':str(exc)})
|
|
raise
|
|
log(title+':返回',{'seconds':round(time.monotonic()-started,3),'result':value})
|
|
return value
|
|
return wrapped
|
|
return decorate
|