opencode/packages/console/function/src/log-processor.ts

63 lines
2.2 KiB
TypeScript
Raw Normal View History

2025-10-05 09:33:39 +08:00
import { Resource } from "@opencode-ai/console-resource"
2025-09-09 03:46:57 +08:00
import type { TraceItem } from "@cloudflare/workers-types"
export default {
async tail(events: TraceItem[]) {
for (const event of events) {
if (!event.event) continue
if (!("request" in event.event)) continue
if (event.event.request.method !== "POST") continue
const url = new URL(event.event.request.url)
2025-09-23 21:15:55 +08:00
if (
url.pathname !== "/zen/v1/chat/completions" &&
url.pathname !== "/zen/v1/messages" &&
2025-11-19 06:42:46 +08:00
url.pathname !== "/zen/v1/responses" &&
!url.pathname.startsWith("/zen/v1/models/")
2025-09-23 21:15:55 +08:00
)
return
2025-09-09 03:46:57 +08:00
2026-02-11 04:55:31 +08:00
let data = {
2025-09-09 03:46:57 +08:00
event_type: "completions",
"cf.continent": event.event.request.cf?.continent,
"cf.country": event.event.request.cf?.country,
"cf.city": event.event.request.cf?.city,
"cf.region": event.event.request.cf?.region,
"cf.latitude": event.event.request.cf?.latitude,
"cf.longitude": event.event.request.cf?.longitude,
"cf.timezone": event.event.request.cf?.timezone,
duration: event.wallTime,
request_length: parseInt(event.event.request.headers["content-length"] ?? "0"),
status: event.event.response?.status ?? 0,
ip: event.event.request.headers["x-real-ip"],
}
2026-02-11 04:55:31 +08:00
const time = event.eventTimestamp ?? Date.now()
const events = []
2025-09-09 03:46:57 +08:00
for (const log of event.logs) {
for (const message of log.message) {
if (!message.startsWith("_metric:")) continue
2026-02-11 04:55:31 +08:00
const json = JSON.parse(message.slice(8))
data = { ...data, ...json }
if ("llm.error.code" in json) {
events.push({ time, data: { ...data } })
}
2025-09-09 03:46:57 +08:00
}
}
2026-02-11 04:55:31 +08:00
events.push({ time, data })
console.log(JSON.stringify(data, null, 2))
2025-09-09 03:46:57 +08:00
2026-02-11 04:55:31 +08:00
const ret = await fetch("https://api.honeycomb.io/1/batch/zen", {
2025-09-09 03:46:57 +08:00
method: "POST",
headers: {
2026-02-11 06:24:03 +08:00
"Content-Encoding": "plaintext",
2025-09-09 03:46:57 +08:00
"Content-Type": "application/json",
"X-Honeycomb-Team": Resource.HONEYCOMB_API_KEY.value,
},
2026-02-11 04:55:31 +08:00
body: JSON.stringify(events),
2025-09-09 03:46:57 +08:00
})
console.log(ret.status)
console.log(await ret.text())
}
},
}