From ff259ec67d9e94cda8fb62fa19ec2932df291d89 Mon Sep 17 00:00:00 2001 From: Eliezer Steinbock <3090527+elie222@users.noreply.github.com> Date: Mon, 30 Dec 2024 09:54:01 +0200 Subject: [PATCH] Log to axiom in prod --- apps/web/utils/logger.ts | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/apps/web/utils/logger.ts b/apps/web/utils/logger.ts index a733b774e..2d5d589dd 100644 --- a/apps/web/utils/logger.ts +++ b/apps/web/utils/logger.ts @@ -1,3 +1,6 @@ +import { log } from "next-axiom"; +import { env } from "@/env"; + type LogLevel = "info" | "error" | "warn" | "trace"; type LogMessage = string | Record; @@ -10,11 +13,13 @@ const colors = { } as const; export function createScopedLogger(scope: string) { + if (env.NEXT_PUBLIC_AXIOM_TOKEN) return createAxiomLogger(scope); + const formatMessage = (level: LogLevel, message: LogMessage) => { const prefix = `[${scope}]: `; if (process.env.NODE_ENV === "development") { - return `${colors[level]}${prefix} ${ + return `${colors[level]}${prefix}${ typeof message === "string" ? message : JSON.stringify(message, null, 2) }${colors.reset}`; } @@ -41,3 +46,26 @@ export function createScopedLogger(scope: string) { }, }; } + +function createAxiomLogger(scope: string) { + function formatMessage(message: LogMessage) { + const prefix = `[${scope}]: `; + return typeof message === "string" + ? `${prefix}${message}` + : `${prefix}${JSON.stringify(message)}`; + } + + return { + info: (message: LogMessage, ...args: unknown[]) => + log.info(formatMessage(message), args.length ? { args } : undefined), + error: (message: LogMessage, ...args: unknown[]) => + log.error(formatMessage(message), args.length ? { args } : undefined), + warn: (message: LogMessage, ...args: unknown[]) => + log.warn(formatMessage(message), args.length ? { args } : undefined), + trace: (message: LogMessage, ...args: unknown[]) => { + if (process.env.NODE_ENV === "development") { + log.debug(formatMessage(message), args.length ? { args } : undefined); + } + }, + }; +}