sendou.ink/app/utils/logger.ts

45 lines
1.2 KiB
TypeScript

/** biome-ignore-all lint/suspicious/noConsole: stub file to enable different solution later */
import { getSessionId as getClientSessionId } from "./session-id";
declare global {
var __getServerSessionId: (() => string | undefined) | undefined;
}
function getSessionIdForLog(): string {
if (typeof window !== "undefined") {
return getClientSessionId();
}
return globalThis.__getServerSessionId?.() ?? "no-session";
}
let infoLogsSilenced = false;
function formatLog(...args: unknown[]) {
const sessionId = getSessionIdForLog();
return [`[${sessionId}]`, ...args];
}
export const logger = {
info: (...args: unknown[]) => {
if (infoLogsSilenced) return;
console.log(...formatLog(...args));
},
error: (...args: unknown[]) => console.error(...formatLog(...args)),
warn: (...args: unknown[]) => console.warn(...formatLog(...args)),
debug: (...args: unknown[]) => {
if (process.env.NODE_ENV === "production") return;
console.debug(...formatLog(...args));
},
};
/** Runs `fn` without its `logger.info` output, warnings and errors still logging. */
export async function withoutInfoLogs<T>(fn: () => Promise<T>): Promise<T> {
infoLogsSilenced = true;
try {
return await fn();
} finally {
infoLogsSilenced = false;
}
}