Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

logger.ts

103 lines2.6 KB

1import util from "node:util";
2​
3type LogLevel = "info" | "warn" | "error" | "event";
4​
5type LogContext = Record<string, unknown>;
6​
7const ANSI = {
8 reset: "\u001b[0m",
9 dim: "\u001b[2m",
10 cyan: "\u001b[36m",
11 yellow: "\u001b[33m",
12 red: "\u001b[31m",
13 magenta: "\u001b[35m",
14} as const;
15​
16const LEVEL_LABEL: Record<LogLevel, string> = {
17 info: "INFO",
18 warn: "WARN",
19 error: "ERROR",
20 event: "EVENT",
21};
22​
23const LEVEL_COLOR: Record<LogLevel, string> = {
24 info: ANSI.cyan,
25 warn: ANSI.yellow,
26 error: ANSI.red,
27 event: ANSI.magenta,
28};
29​
30function useColors() {
31 return Boolean(process.stdout.isTTY) && process.env.NO_COLOR === undefined;
33​
34function colorize(value: string, color: string, enabled: boolean) {
35 return enabled ? `${color}${value}${ANSI.reset}` : value;
37​
38function timeStamp() {
39 return new Date().toISOString().slice(11, 23);
41​
42function formatValue(value: unknown) {
43 if (typeof value === "string") {
44 return JSON.stringify(value);
45 }
46 if (
47 typeof value === "number" ||
48 typeof value === "boolean" ||
49 value === null ||
50 value === undefined
51 ) {
52 return String(value);
53 }
54 return util.inspect(value, {
55 depth: 4,
56 breakLength: Infinity,
57 compact: true,
58 maxArrayLength: 25,
59 maxStringLength: 320,
60 });
62​
63function formatContext(context: LogContext | undefined) {
64 if (!context) return "";
65 const entries = Object.entries(context).filter(([, value]) => value !== undefined);
66 if (entries.length === 0) return "";
67 return entries.map(([key, value]) => `${key}=${formatValue(value)}`).join(" ");
69​
70function write(level: LogLevel, scope: string, message: string, context?: LogContext) {
71 const colorEnabled = useColors();
72 const ts = colorize(timeStamp(), ANSI.dim, colorEnabled);
73 const levelLabel = colorize(LEVEL_LABEL[level], LEVEL_COLOR[level], colorEnabled);
74 const contextText = formatContext(context);
75 const line = `${ts} ${levelLabel} [${scope}] ${message}${contextText ? ` ${contextText}` : ""}`;
76​
77 if (level === "warn") {
78 console.warn(line);
79 return;
80 }
81 if (level === "error") {
82 console.error(line);
83 return;
84 }
85 console.log(line);
87​
88export function createLogger(scope: string) {
89 return {
90 info(message: string, context?: LogContext) {
91 write("info", scope, message, context);
92 },
93 warn(message: string, context?: LogContext) {
94 write("warn", scope, message, context);
95 },
96 error(message: string, context?: LogContext) {
97 write("error", scope, message, context);
98 },
99 event(message: string, context?: LogContext) {
100 write("event", scope, message, context);
101 },
102 };