From 8fe2b9cb27ead4200b30989711765d875dc9a3c8 Mon Sep 17 00:00:00 2001 From: Manav Rathi Date: Sat, 15 Jun 2024 18:27:44 +0530 Subject: [PATCH] The protocol --- infra/workers/tail/src/index.ts | 45 ++++++++++++++++++++++++++++---- infra/workers/tail/wrangler.toml | 2 +- 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/infra/workers/tail/src/index.ts b/infra/workers/tail/src/index.ts index 3f73e870b0..de3c019fe2 100644 --- a/infra/workers/tail/src/index.ts +++ b/infra/workers/tail/src/index.ts @@ -4,16 +4,51 @@ * https://developers.cloudflare.com/workers/observability/logging/tail-workers/ */ export default { - async tail(events: TailItems[], env: Env) { + async tail(events: TraceItem[], env: Env) { // If the tail worker itself throws an exception (it shouldn't, unless // Loki is down), we don't catch it so that it counts as an "error" in // the worker stats. - return handleTail(events, env.LOKI_URL); + return handleTail(events, env.LOKI_PUSH_URL); }, -} satisfies ExportedHander; +} satisfies ExportedHandler; interface Env { - LOKI_URL: string; + LOKI_PUSH_URL: string; } -const handleTail = (events: TailItems[], lokiURL: string) => {}; +const handleTail = async (events: TraceItem[], lokiPushURL: string) => {}; + +/** + * Send a log entry to (Grafana) Loki + * + * For more details about the protocol, see + * https://grafana.com/docs/loki/latest/reference/loki-http-api/#ingest-logs + * + * @param tsNano Unix epoch in nanoseconds when the event occurred. + * + * @param logLine The message to log. + * + * @param lokiPushURL The URL of the Loki instance to push logs to. The + * credentials are part of the URL. + */ +const pushLogLine = async ( + tsNano: number, + logLine: string, + lokiPushURL: string +) => + fetch(lokiPushURL, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + streams: [ + { + stream: { + job: "cf-worker", + }, + values: [[`${tsNano}`, logLine]], + }, + ], + }), + }); diff --git a/infra/workers/tail/wrangler.toml b/infra/workers/tail/wrangler.toml index 14c8b92083..bd0326dccb 100644 --- a/infra/workers/tail/wrangler.toml +++ b/infra/workers/tail/wrangler.toml @@ -4,4 +4,4 @@ compatibility_date = "2024-06-14" [vars] # Added as a secret via the Cloudflare dashboard -# LOKI_URL = "https://discord.com/api/webhooks/{webhook.id}/{webhook.token}" +# LOKI_PUSH_URL = "https://{loki_base_url}>/loki/api/v1/push"