|
| 1 | +import { z } from "zod" |
| 2 | +import { baseLogSchema } from "./schemas" |
| 3 | + |
| 4 | +function buildJson<T extends {}>(logs: Array<Partial<T>>) { |
| 5 | + const logsObj: Record<string, unknown> = {} |
| 6 | + for (let i = 0; i < logs.length; i++) { |
| 7 | + Object.entries(logs[i]).forEach(([key, value]) => { |
| 8 | + logsObj[key] = value |
| 9 | + }) |
| 10 | + } |
| 11 | + return logsObj as T |
| 12 | +} |
| 13 | + |
| 14 | +function buildText<T>(logs: Array<Partial<T>>) { |
| 15 | + const jsonLine = buildJson(logs) |
| 16 | + return Object.entries(jsonLine) |
| 17 | + .map(([key, value]) => `${key}=${JSON.stringify(value)}`) |
| 18 | + .join(" ") |
| 19 | +} |
| 20 | + |
| 21 | +export type FlytrapLogsOptions = { |
| 22 | + /** |
| 23 | + * The format in which to log out the canonical log line. |
| 24 | + * |
| 25 | + * @default 'json' |
| 26 | + * |
| 27 | + * The JSON format is as follows: |
| 28 | + * @example |
| 29 | + * ```json |
| 30 | + * { |
| 31 | + * "http_status": 200, |
| 32 | + * "user_id": "abcd" |
| 33 | + * } |
| 34 | + * ``` |
| 35 | + * |
| 36 | + * The `text` format looks like this: |
| 37 | + * @example |
| 38 | + * ``` |
| 39 | + * http_status=200 user_id=abcd |
| 40 | + * ``` |
| 41 | + */ |
| 42 | + format?: "json" | "text" |
| 43 | + |
| 44 | + /** |
| 45 | + * Whether to simply flush the logs to stdout / stderr, or to send them to an API. |
| 46 | + * |
| 47 | + * If `flushMethod` is `'api'`, the log format will default to `'json'`. |
| 48 | + * |
| 49 | + * If you're using our Logs Vercel Integration, this should be `'stdout'` |
| 50 | + */ |
| 51 | + flushMethod?: "stdout" | "api" |
| 52 | + |
| 53 | + /** |
| 54 | + * If the `flushMethod` is `'api'`, the logs will be sent to this endpoint with a POST request with a JSON payload. |
| 55 | + * The schema for the request can be found @TODO |
| 56 | + */ |
| 57 | + logsEndpoint?: string |
| 58 | + |
| 59 | + /** |
| 60 | + * The Flytrap public key used to authenticate your requests. |
| 61 | + */ |
| 62 | + flytrapPublicKey?: string |
| 63 | +} |
| 64 | + |
| 65 | +export type FlushLevel = "error" | "warn" | "log" |
| 66 | + |
| 67 | +export function createFlytrapLogger<T>({ |
| 68 | + format = "json", |
| 69 | + flushMethod = "api", |
| 70 | + logsEndpoint = "https://flytrap-production.up.railway.app/api/v1/logs/raw", |
| 71 | + flytrapPublicKey, |
| 72 | +}: FlytrapLogsOptions = {}) { |
| 73 | + const logFormat: FlytrapLogsOptions["format"] = |
| 74 | + flushMethod === "api" ? "json" : format |
| 75 | + |
| 76 | + type Log = z.infer<typeof baseLogSchema> & T |
| 77 | + const defaultLog = { |
| 78 | + type: "request", |
| 79 | + path: "PATH_UNDEFINED", |
| 80 | + req: null, |
| 81 | + req_headers: {}, |
| 82 | + res: null, |
| 83 | + res_headers: {}, |
| 84 | + http_status: 200, |
| 85 | + duration: 0, |
| 86 | + method: "GET", |
| 87 | + } satisfies z.infer<typeof baseLogSchema> |
| 88 | + |
| 89 | + let logs: Array<Partial<Log>> = [defaultLog as Log] |
| 90 | + |
| 91 | + return { |
| 92 | + getContext() { |
| 93 | + return logs |
| 94 | + }, |
| 95 | + addContext(context: Partial<Log>) { |
| 96 | + logs.push(context) |
| 97 | + }, |
| 98 | + flush(level: FlushLevel = "log") { |
| 99 | + try { |
| 100 | + const logValue = |
| 101 | + logFormat === "text" ? buildText(logs) : buildJson(logs) |
| 102 | + |
| 103 | + if (flushMethod === "stdout") { |
| 104 | + console[level]( |
| 105 | + typeof logValue === "string" ? logValue : JSON.stringify(logValue) |
| 106 | + ) |
| 107 | + } |
| 108 | + if (flushMethod === "api") { |
| 109 | + fetch(logsEndpoint, { |
| 110 | + method: "POST", |
| 111 | + body: JSON.stringify(logValue), |
| 112 | + headers: new Headers({ |
| 113 | + "Content-Type": "application/json", |
| 114 | + ...(flytrapPublicKey && { |
| 115 | + Authorization: `Bearer ${flytrapPublicKey}`, |
| 116 | + }), |
| 117 | + }), |
| 118 | + }).then(async (res) => { |
| 119 | + if (res.ok === false) { |
| 120 | + console.error( |
| 121 | + "Flytrap Logs SDK: Failed to save logs to API. Error:" |
| 122 | + ) |
| 123 | + console.error(await res.text()) |
| 124 | + } |
| 125 | + }) |
| 126 | + } |
| 127 | + } catch (error) { |
| 128 | + console.error("Flytrap Logs SDK: Error when flushing logs. Error:") |
| 129 | + console.error(error) |
| 130 | + } |
| 131 | + }, |
| 132 | + } |
| 133 | +} |
0 commit comments