Logáil agus Inbhreathnaitheacht
Ar an leathanach seo
Logáil agus Inbhreathnaitheacht
I dtimpeallacht táirgeachta, ní mór duit a bheith ar an eolas go beacht faoin méid atá ag tarlú le do ghlaonna API: moill, toicíní a úsáideadh, earráidí, agus costais. Tugann logáil struchtúrtha agus inbhreathnaitheacht an radharc sin duit. Éiríonn an difríocht soiléir an tsoicind a thuairiscíonn úsáideoir, “Tá an cúntóir mall ó mhaidin inniu.” Gan ionstraimíocht, beidh ort buille faoi thuairim a dhéanamh. Leis na huirlisí cearta, feicfidh tú laistigh de thríocha soicind go ndearna moill p95 dúbailt tar éis athrú pras a thriplaigh méid an chomhthéacs.
Bunlogáil Struchtúrtha
Déan nós de thomhas a dhéanamh timpeall an ghlao, ní laistigh de. Taifead an clog roimh ré, léigh arís é ina dhiaidh, agus eisigh líne amháin a chuireann síos ar an imeacht iomlán. Níl JSON ann ach le taispeáint: ligeann sé do d’fhreastalaí comhiomlánaithe scagadh de réir status, rianú duration_ms le himeacht ama, nó response_id ar leith a aimsiú—rud nach féidir le téacs saorchruthach a dhéanamh riamh. Cruthaíonn an bloc except an struchtúr céanna go díreach, lena n-áirítear cineál agus teachtaireacht an eisceachta, agus ansin déanann sé athardú air. Ní hionann logáil agus láimhseáil earráidí.
import logging
import json
import time
from openai import OpenAI
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s"
)
logger = logging.getLogger("openai_api")
client = OpenAI()
def appel_avec_logging(prompt: str, model: str = "gpt-5.6-terra") -> str:
"""API call with full structured logging."""
start = time.monotonic()
request_id = None
try:
response = client.responses.create(
model=model,
input=prompt
)
duree = time.monotonic() - start
logger.info(json.dumps({
"event": "api_call",
"status": "success",
"model": response.model,
"response_id": response.id,
"input_tokens": response.usage.input_tokens,
"output_tokens": response.usage.output_tokens,
"total_tokens": response.usage.total_tokens,
"duration_ms": round(duree * 1000),
"prompt_length": len(prompt),
}))
return response.output_text
except Exception as e:
duree = time.monotonic() - start
logger.error(json.dumps({
"event": "api_call",
"status": "error",
"error_type": type(e).__name__,
"error_message": str(e),
"model": model,
"duration_ms": round(duree * 1000),
"prompt_length": len(prompt),
}))
raise
resultat = appel_avec_logging("Hello!")
Tabhair faoi deara go ndéanaimid logáil ar prompt_length, ní ar an bpras féin. Is rogha dearaidh é sin, ní dearmad: tá an fhad leordhóthanach chun comhcheangal a dhéanamh le moill, gan sonraí úsáideora a onnmhairiú chuig do chóras logála.
Meánach Logála
Má athdhéanann tú an bloc seo i ngach feidhm a ghlaonn ar an API, is cinnte go ndéanfaidh tú dearmad air in áit éigin. Is fearr an cliant a chur i gclúdach uair amháin agus go deo. Sainíonn an tacar sonraí APIMetrics an conradh maidir leis an méid a thomhaiseann muid, agus líonann ObservableClient an taifead sin agus déanann sé cartlann de, cibé acu a éiríonn leis an nglao nó a theipeann air. Ansin, tiontaíonn an modh rapport an stair ina mheadráin atá inbhfeidhmithe go díreach—ráta ratha, meánmhoill, moill p95.
Is é an uimhir dheireanach sin an ceann is tábhachtaí. Is féidir le meán 450 ms an t-úsáideoir amháin as fiche atá ag fanacht trí shoicind a cheilt; nochtann p95 é. Trí fhadanna a shórtáil agus an luach ag an 95ú céatadán a ghlacadh, déanann tú cur síos ar an bhfíor-eispéireas atá ag d’úsáideoirí gníomhacha is measa a seirbhíseadh.
from dataclasses import dataclass, field
from typing import Optional
import time
import json
@dataclass
class APIMetrics:
"""Metrics collected for each call."""
model: str = ""
input_tokens: int = 0
output_tokens: int = 0
total_tokens: int = 0
duration_ms: int = 0
status: str = "unknown"
error: Optional[str] = None
response_id: Optional[str] = None
class ObservableClient:
"""OpenAI client with built-in observability."""
def __init__(self):
self.client = OpenAI()
self.metrics_history: list[APIMetrics] = []
def create(self, model: str, input: str, **kwargs) -> object:
start = time.monotonic()
metrics = APIMetrics(model=model)
try:
response = self.client.responses.create(
model=model,
input=input,
**kwargs
)
metrics.status = "success"
metrics.response_id = response.id
metrics.input_tokens = response.usage.input_tokens
metrics.output_tokens = response.usage.output_tokens
metrics.total_tokens = response.usage.total_tokens
metrics.duration_ms = round((time.monotonic() - start) * 1000)
self.metrics_history.append(metrics)
return response
except Exception as e:
metrics.status = "error"
metrics.error = str(e)
metrics.duration_ms = round((time.monotonic() - start) * 1000)
self.metrics_history.append(metrics)
raise
def rapport(self) -> dict:
"""Generate a report of collected metrics."""
if not self.metrics_history:
return {"message": "No calls recorded"}
total_calls = len(self.metrics_history)
erreurs = sum(1 for m in self.metrics_history if m.status == "error")
total_tokens = sum(m.total_tokens for m in self.metrics_history)
durees = [m.duration_ms for m in self.metrics_history]
return {
"total_appels": total_calls,
"erreurs": erreurs,
"taux_succes": f"{((total_calls - erreurs) / total_calls) * 100:.1f}%",
"total_tokens": total_tokens,
"latence_moyenne_ms": round(sum(durees) / len(durees)),
"latence_p95_ms": sorted(durees)[int(len(durees) * 0.95)],
}
# Usage
obs_client = ObservableClient()
obs_client.create("gpt-5.6-terra", "Hello!")
obs_client.create("gpt-5.6-terra", "How are you?")
obs_client.create("gpt-5.6-terra", "Thanks!")
print(json.dumps(obs_client.rapport(), indent=2))
# Result:
# {
# "total_appels": 3,
# "erreurs": 0,
# "taux_succes": "100.0%",
# "total_tokens": 95,
# "latence_moyenne_ms": 450,
# "latence_p95_ms": 520
# }
Rianú Glaonna le Comhthéacs
I ngníomhaireacht dháilte, ní bhíonn glao API ann riamh ina aonar: spreagtar é le hiarratas HTTP, a eascraíonn as gníomh úsáideora féin, agus uaireanta leanann dhá ghlao eile é. Is é an trace_id an snáithe a cheanglaíonn na himeachtaí seo le chéile. Trí é a scaipeadh ó do shraith ghréasáin—anseo user-123-req-456—is féidir leat seisiún iomlán a athchruthú i do logaí ó ghearán custaiméara amháin. Eisítear dhá líne, ceann ag an tús agus ceann ag an gcríoch, rud a chuidíonn freisin le glaonna a aimsiú nár fhill riamh.
import uuid
class TracingClient:
"""Client with tracing to correlate requests."""
def __init__(self):
self.client = OpenAI()
def create_with_trace(self, prompt: str, trace_id: str = None,
**kwargs) -> tuple:
"""Call with trace_id for correlation."""
if trace_id is None:
trace_id = str(uuid.uuid4())[:8]
start = time.monotonic()
logger.info(json.dumps({
"event": "api_request_start",
"trace_id": trace_id,
"prompt_preview": prompt[:100],
}))
response = self.client.responses.create(
model=kwargs.get("model", "gpt-5.6-terra"),
input=prompt,
**{k: v for k, v in kwargs.items() if k != "model"}
)
duration = time.monotonic() - start
logger.info(json.dumps({
"event": "api_request_complete",
"trace_id": trace_id,
"response_id": response.id,
"tokens": response.usage.total_tokens,
"duration_ms": round(duration * 1000),
}))
return response, trace_id
# Usage with trace_id to correlate in logs
tracing = TracingClient()
response, trace = tracing.create_with_trace(
"Summarize logging best practices.",
trace_id="user-123-req-456"
)
print(f"Trace: {trace} | Response: {response.output_text[:80]}...")
Bí cúramach le prompt_preview: téann na chéad chéad carachtar sin díreach isteach i do logaí mar atá siad. Glacthar leis i bhforbairt, ach bain é chomh luath agus a bhíonn fíor-shonraí á sreabhadh.
Onnmhairiú chuig Córas Monatóireachta
Imíonn stair atá i gcuimhne nuair a atosóidh an próiseas. Chun seirbhís a mhonatóiriú le himeacht ama, ní mór duit meadráin a nochtadh d’uirlis sheachtrach. Braitheann an patrún uilíoch ar dhá theaghlach: áiritheoirí, nach méadaíonn ach a dhíorthaítear ina rátaí, agus histeagraim, a choinníonn dáileadh chun céatadáin a bhaint amach. Tá an rang seo neodrach d’aon ghnó—ní gá duit ach get_metrics a nascadh le críochphointe ionas go scrúdóidh Prometheus é, nó an foclóir a bhrú chuig Datadog.
# Pattern for exporting to Prometheus, Datadog, etc.
class MetricsExporter:
"""Metrics exporter compatible with monitoring systems."""
def __init__(self):
self.counters = {
"api_calls_total": 0,
"api_errors_total": 0,
"tokens_consumed_total": 0,
}
self.histograms = {
"api_latency_ms": [],
}
def record_success(self, tokens: int, latency_ms: int):
self.counters["api_calls_total"] += 1
self.counters["tokens_consumed_total"] += tokens
self.histograms["api_latency_ms"].append(latency_ms)
def record_error(self):
self.counters["api_calls_total"] += 1
self.counters["api_errors_total"] += 1
def get_metrics(self) -> dict:
latencies = self.histograms["api_latency_ms"]
return {
**self.counters,
"latency_avg_ms": round(sum(latencies) / max(len(latencies), 1)),
"error_rate": self.counters["api_errors_total"] /
max(self.counters["api_calls_total"], 1),
}
exporter = MetricsExporter()
# Call exporter.record_success() or exporter.record_error()
# after each API call
Príomhphointí
- Déan logáil ar gach glao le: múnla, toicíní, moill, stádas, response_id
- Úsáid JSON struchtúrtha do logaí is féidir le d’uirlisí a pharsáil
- Bailigh meadráin thábhachtacha: ráta ratha, moill p95, tomhaltas toicíní
- Cuir
trace_idleis chun iarratais a chomhcheangal i gcórais dháilte - Onnmhairigh meadráin chuig do chóras monatóireachta (Prometheus, Datadog, srl.)
- Ná déan logáil riamh ar ábhar prais i dtimpeallacht táirgeachta (sonraí íogaire)