99 lines
3.0 KiB
TypeScript
99 lines
3.0 KiB
TypeScript
//reused logger from other projects but use for only deployment logging
|
|
|
|
import { feature } from "bun:bundle";
|
|
import { styleText } from "node:util";
|
|
|
|
import { inspect } from "bun";
|
|
|
|
type InspectColor = Extract<Parameters<typeof styleText>[0], string>;
|
|
|
|
const colors: InspectColor[] = [
|
|
"red",
|
|
"green",
|
|
"yellow",
|
|
"blue",
|
|
"magenta",
|
|
"cyan",
|
|
"white",
|
|
"redBright",
|
|
"greenBright",
|
|
"yellowBright",
|
|
"blueBright",
|
|
"magentaBright",
|
|
"cyanBright",
|
|
"whiteBright",
|
|
];
|
|
var i = 0;
|
|
|
|
// 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;
|
|
function mkLogFn(stream: Console | NodeJS.WriteStream, strip?: InspectColor) {
|
|
return (strings: TemplateStringsArray, ...values: unknown[]) => {
|
|
const tty = stream === console ? process.stdout.isTTY : process.stderr.isTTY;
|
|
if (!tty) {
|
|
const prefix = `${(label ?? `${Date.now() - start}ms`).padStart(7)} ▌${strip ? "▌" : " "}`;
|
|
let message = strings.reduce(
|
|
(out, str, index) =>
|
|
out + str +
|
|
(typeof values[index] === "string"
|
|
? values[index]
|
|
: typeof values[index] !== "undefined"
|
|
? inspect(values[index], { colors: false })
|
|
: ""),
|
|
"",
|
|
);
|
|
message = message.split("\n").join(`\n${" ".repeat(7)} ▌${strip ? "▌" : " "}`);
|
|
(stream.write as (data: string) => void)(`${prefix}${message}\n`);
|
|
return;
|
|
}
|
|
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 const log = createLogger("APP");
|