웹 로그, DB 쿼리문과 결과 로그 출력
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
type Level = "debug" | "info" | "warn" | "error";
|
||||
|
||||
const PRIORITY: Record<Level, number> = {
|
||||
debug: 0,
|
||||
info: 1,
|
||||
warn: 2,
|
||||
error: 3,
|
||||
};
|
||||
|
||||
function getMinLevel(): Level {
|
||||
const env = process.env.LOG_LEVEL as Level | undefined;
|
||||
if (env && env in PRIORITY) return env;
|
||||
const appEnv = process.env.APP_ENV;
|
||||
return appEnv === "production" ? "info" : "debug";
|
||||
}
|
||||
|
||||
function shouldLog(level: Level): boolean {
|
||||
return PRIORITY[level] >= PRIORITY[getMinLevel()];
|
||||
}
|
||||
|
||||
function write(
|
||||
level: Level,
|
||||
ctx: string,
|
||||
message: string,
|
||||
data?: Record<string, unknown>
|
||||
): void {
|
||||
if (!shouldLog(level)) return;
|
||||
const ts = new Date().toISOString();
|
||||
const tag = level.toUpperCase().padEnd(5);
|
||||
const line = data
|
||||
? `[${ts}] [${tag}] [${ctx}] ${message} ${JSON.stringify(data)}`
|
||||
: `[${ts}] [${tag}] [${ctx}] ${message}`;
|
||||
if (level === "warn" || level === "error") {
|
||||
console.error(line);
|
||||
} else {
|
||||
console.log(line);
|
||||
}
|
||||
}
|
||||
|
||||
export const logger = {
|
||||
debug: (ctx: string, message: string, data?: Record<string, unknown>) =>
|
||||
write("debug", ctx, message, data),
|
||||
info: (ctx: string, message: string, data?: Record<string, unknown>) =>
|
||||
write("info", ctx, message, data),
|
||||
warn: (ctx: string, message: string, data?: Record<string, unknown>) =>
|
||||
write("warn", ctx, message, data),
|
||||
error: (ctx: string, message: string, data?: Record<string, unknown>) =>
|
||||
write("error", ctx, message, data),
|
||||
isEnabled: (level: Level): boolean => shouldLog(level),
|
||||
};
|
||||
Reference in New Issue
Block a user