Skip to content

Commit

Permalink
Log to axiom in prod
Browse files Browse the repository at this point in the history
  • Loading branch information
elie222 committed Dec 30, 2024
1 parent e7a7507 commit ff259ec
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion apps/web/utils/logger.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { log } from "next-axiom";
import { env } from "@/env";

type LogLevel = "info" | "error" | "warn" | "trace";
type LogMessage = string | Record<string, unknown>;

Expand All @@ -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}`;
}
Expand All @@ -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);
}
},
};
}

0 comments on commit ff259ec

Please sign in to comment.