Skip to content

Instantly share code, notes, and snippets.

@GodderE2D
Last active February 2, 2022 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GodderE2D/088b3960d6bac34c1cb18e4c8b26700b to your computer and use it in GitHub Desktop.
Save GodderE2D/088b3960d6bac34c1cb18e4c8b26700b to your computer and use it in GitHub Desktop.
TypeScript simple logger that logs to stdout, easily customisable to your needs.
/* eslint-disable no-console */
// ⚠️ The chalk dependency is required to function: "npm i chalk" or "yarn add chalk" or "pnpm add chalk"
import { stderr, stdout } from "node:process";
import EventEmitter from "node:events";
import chalk from "chalk";
import { inspect } from "node:util";
import { setImmediate } from "node:timers";
type LogType = "debug" | "info" | "warn" | "error";
type LogEventProperties = {
type: LogType;
date: Date;
timestamp: number;
output: string;
coloredOutput: string;
rawOutput: unknown;
};
class Logger extends EventEmitter {
private runPrerequisites(
message: unknown,
thisObject: Logger
): { output: string; coloredOutput: string } {
const output =
typeof message === "string" ? message : inspect(message, true, 5);
const coloredOutput =
typeof message === "string" ? message : inspect(message, true, 5, true);
const logEventProperties: LogEventProperties = {
type: "info",
date: new Date(),
timestamp: Date.now() / 1000,
output: output,
coloredOutput: coloredOutput,
rawOutput: message,
};
thisObject.emit("log", logEventProperties);
return {
output,
coloredOutput,
};
}
public constructor() {
super();
this.info("Logger initialized.");
}
public debug(message: unknown): void {
const { output, coloredOutput } = this.runPrerequisites(message, this);
if (stdout.hasColors()) {
setImmediate(() => {
stdout.write(`${chalk.cyan("debug")} - ${coloredOutput}\n`);
});
} else {
setImmediate(() => {
stdout.write(`debug - ${output}\n`);
});
}
}
public info(message: unknown): void {
const { output, coloredOutput } = this.runPrerequisites(message, this);
if (stdout.hasColors()) {
setImmediate(() => {
stdout.write(`${chalk.blue("info")} - ${coloredOutput}\n`);
});
} else {
setImmediate(() => {
stdout.write(`info - ${output}\n`);
});
}
}
public warn(message: unknown): void {
const { output, coloredOutput } = this.runPrerequisites(message, this);
if (stderr.hasColors()) {
setImmediate(() => {
stderr.write(`${chalk.yellow("warn")} - ${coloredOutput}\n`);
});
} else {
setImmediate(() => {
stderr.write(`warn - ${output}\n`);
});
}
}
public error(message: unknown): void {
const { output, coloredOutput } = this.runPrerequisites(message, this);
if (stderr.hasColors()) {
setImmediate(() => {
stderr.write(`${chalk.red("error")} - ${coloredOutput}\n`);
});
} else {
setImmediate(() => {
stderr.write(`error - ${output}\n`);
});
}
}
}
export default Logger;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment