feat: new logger yo

This commit is contained in:
2026-04-25 17:43:35 +07:00 Unverified
parent a2f8987e02
commit e751b9b4b8
+44 -24
View File
@@ -1,5 +1,6 @@
import { feature } from "bun:bundle";
import { InspectColor, styleText } from "node:util";
import { inspect } from "bun";
const colors: InspectColor[] = [
@@ -20,36 +21,55 @@ const colors: InspectColor[] = [
];
var i = 0;
if (!feature("API"))
if (!feature("prod"))
console.log(
colors.map((c, i) => styleText(c, (i + 10).toString(36))).join(""),
);
export type Logger = {
(strings: TemplateStringsArray, ...values: unknown[]): void;
error(strings: TemplateStringsArray, ...values: unknown[]): void;
warn(strings: TemplateStringsArray, ...values: unknown[]): void;
debug(strings: TemplateStringsArray, ...values: unknown[]): void;
};
export function createLogger(label?: string) {
const start = Date.now();
const col = colors[i];
i = (i + 1) % colors.length;
return function log(strings: TemplateStringsArray, ...values: unknown[]) {
const normalized = styleText(
col,
`${(label ?? `${Date.now() - start}ms`).padStart(7)} | ${strings
.reduce(
(out, str, i) =>
out +
str +
(typeof values[i] === "string"
? values[i]
: typeof values[i] !== "undefined"
? inspect(values[i], { colors: true })
: ""),
"",
)
.split("\n")
.map((l, i) => styleText(col, i ? `${" ".repeat(7)} | ${l}` : l))
.join("\n")}\n`,
);
console.write(normalized);
};
function mkLogFn(stream: Console | NodeJS.WriteStream, strip?: InspectColor) {
return (strings: TemplateStringsArray, ...values: unknown[]) => {
const normalized = styleText(
col,
`${(strip ? styleText : (_: string, s: string) => s)("bold", (label ?? `${Date.now() - start}ms`).padStart(7))} ▌${strip ? styleText(strip, "▌") : " "}${strings
.reduce(
(out, str, i) =>
out +
styleText(col, str) +
(typeof values[i] === "string"
? values[i]
: typeof values[i] !== "undefined"
? inspect(values[i], { colors: true })
: ""),
"",
)
.split("\n")
.map((l, i) =>
styleText(
col,
i
? `${" ".repeat(7)} ▌${strip ? styleText(strip, "▌") : " "}${l}`
: l,
),
)
.join("\n")}\n`,
);
(stream.write as (data: string) => void)(normalized);
};
}
const log = mkLogFn(console) as Logger;
log.error = mkLogFn(process.stderr, "redBright");
log.warn = mkLogFn(console, "yellow");
log.debug = feature("prod") ? () => {} : mkLogFn(console, "blue");
return log;
}
export type Logger = ReturnType<typeof createLogger>;