This commit is contained in:
Manav Rathi 2024-06-15 22:49:35 +05:30
parent 07f0cc9342
commit 2b490fe131
No known key found for this signature in database
3 changed files with 35 additions and 51 deletions

View File

@ -2,7 +2,6 @@
export default { export default {
async fetch(request: Request) { async fetch(request: Request) {
console.log("This message should appear in the logs.");
switch (request.method) { switch (request.method) {
case "OPTIONS": case "OPTIONS":
return handleOPTIONS(request); return handleOPTIONS(request);
@ -10,7 +9,6 @@ export default {
return handleGET(request); return handleGET(request);
default: default:
console.log(`Unsupported HTTP method ${request.method}`); console.log(`Unsupported HTTP method ${request.method}`);
throw new Error("Unsupported HTTP method");
return new Response(null, { status: 405 }); return new Response(null, { status: 405 });
} }
}, },
@ -30,7 +28,6 @@ const handleOPTIONS = (request: Request) => {
}; };
const isAllowedOrigin = (origin: string | null) => { const isAllowedOrigin = (origin: string | null) => {
console.log(origin);
if (!origin) return false; if (!origin) return false;
try { try {
const url = new URL(origin); const url = new URL(origin);

View File

@ -4,29 +4,38 @@
* https://developers.cloudflare.com/workers/observability/logging/tail-workers/ * https://developers.cloudflare.com/workers/observability/logging/tail-workers/
*/ */
export default { export default {
async tail(events: TraceItem[], env: Env, ctx: ExecutionContext) { async tail(events: TraceItem[], env: Env) {
console.log("Length of LOKI_PUSH_URL", env.LOKI_PUSH_URL.length);
// If the tail worker itself throws an exception (it shouldn't, unless // 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 // Loki is down), we don't catch it so that it counts as an "error" in
// the worker stats. // the worker stats.
ctx.waitUntil(handleTail(events, env.LOKI_PUSH_URL, env.LOKI_AUTH)); await handleTail(events, env);
}, },
} satisfies ExportedHandler<Env>; } satisfies ExportedHandler<Env>;
interface Env { interface Env {
/** The URL of the Loki instance to push logs to. */
LOKI_PUSH_URL: string; LOKI_PUSH_URL: string;
/**
* The value of the "Basic" authorization.
*
* [Note: HTTP basic authorization in worker fetch]
*
* Usually a Loki push URL is specified with the credentials inline, say
* `http://user:pass@loki/path`. However, I cannot get that to work with the
* `fetch` inside a Cloudflare worker. Instead, the credentials need to be
* separately provided as the Authorization header of the form:
*
* Authorization: Basic ${btoa(user:pass)}
*
* The LOKI_AUTH secret is the "${btoa(user:pass)}" value.
*/
LOKI_AUTH: string; LOKI_AUTH: string;
} }
const handleTail = async (events: TraceItem[], lokiPushURL: string, lokiAuth: string) => const handleTail = async (events: TraceItem[], env: Env) => {
await pushLogLine(Date.now(), JSON.stringify(events), lokiPushURL, lokiAuth); for (const event of events.filter(hasLogOrException))
await pushLogLine(Date.now(), JSON.stringify(event), env);
// const handleTail1 = async (events: TraceItem[], lokiPushURL: string) => { };
// for (const event of events.filter(hasLogOrException)) {
// await pushLogLine(Date.now(), JSON.stringify(event), lokiPushURL);
// }
// };
/** Return true if the {@link event} has at least one log or exception. */ /** Return true if the {@link event} has at least one log or exception. */
const hasLogOrException = (event: TraceItem) => const hasLogOrException = (event: TraceItem) =>
@ -42,45 +51,22 @@ const hasLogOrException = (event: TraceItem) =>
* *
* @param logLine The message to log. * @param logLine The message to log.
* *
* @param lokiPushURL The URL of the Loki instance to push logs to. The * @param env The worker environment; we need it for the Loki URL and
* credentials are part of the URL. * credentials.
*/ */
const pushLogLine = async ( const pushLogLine = async (timestampMs: number, logLine: string, env: Env) =>
timestampMs: number, await fetch(env.LOKI_PUSH_URL, {
logLine: string, method: "POST",
lokiPushURL: string, headers: {
lokiAuth: string, "Content-Type": "application/json",
) => { Authorization: `Basic ${env.LOKI_AUTH}`,
console.log( },
"Pushing", body: JSON.stringify({
JSON.stringify({
streams: [ streams: [
{ {
stream: { job: "worker" }, stream: { job: "worker" },
values: [[`${timestampMs * 1e6}`, logLine]], values: [[`${timestampMs * 1e6}`, logLine]],
}, },
], ],
}) }),
); });
try {
const res = await fetch(lokiPushURL, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Basic ${lokiAuth}`,
},
body: JSON.stringify({
streams: [
{
stream: { job: "worker" },
values: [[`${timestampMs * 1e6}`, logLine]],
},
],
}),
});
console.log(res.status, await res.text()); //JSON.stringify(res));
return res;
} catch (e) {
console.log("Failed", e);
}
};

View File

@ -4,4 +4,5 @@ compatibility_date = "2024-06-14"
[vars] [vars]
# Added as a secret via the Cloudflare dashboard # Added as a secret via the Cloudflare dashboard
# LOKI_PUSH_URL = "https://{loki_base_url}>/loki/api/v1/push" # LOKI_PUSH_URL = "https://${loki_base_url}>/loki/api/v1/push"
# LOKI_AUTH = "${btoa(user:pass)}"