Last active
April 16, 2024 20:35
-
-
Save NotoriousPyro/4a029767c826841c523f6dd2375476e6 to your computer and use it in GitHub Desktop.
Asynchonrous Promise-based logger
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// By Pyro @ www.sexonsol.com | |
import { Console } from "node:console"; | |
/** Asynchronous Promise-based logger */ | |
export default class Logger extends Console { | |
public name: string; | |
constructor(name: string) { | |
super({ | |
stdout: process.stdout, | |
stderr: process.stderr, | |
ignoreErrors: true, // Ignore errors writing to the stream | |
}); | |
this.name = name; | |
}; | |
public formatMessage = async (message: string) => `[${new Date().toISOString()}] [${this.name}]: ${message}`; | |
public override info: typeof console.info = async (...args) => this.log(...args); | |
public override log: typeof console.log = async (...args) => | |
new Promise(async (resolve, _) => { | |
const [message, ...rest] = args; | |
const formattedMessage = await this.formatMessage(message); | |
rest.length > 0 | |
? console.log(formattedMessage, ...rest) | |
: console.log(formattedMessage); | |
return resolve(void 0); | |
}); | |
public override error: typeof console.error = async (...args) => | |
new Promise(async (resolve, _) => { | |
const [message, ...rest] = args; | |
const formattedMessage = await this.formatMessage(message); | |
rest.length > 0 | |
? console.error(formattedMessage, ...rest) | |
: console.error(formattedMessage); | |
return resolve(void 0); | |
}); | |
public override warn: typeof console.warn = async (...args) => | |
new Promise(async (resolve, _) => { | |
const [message, ...rest] = args; | |
const formattedMessage = await this.formatMessage(message); | |
rest.length > 0 | |
? console.warn(formattedMessage, ...rest) | |
: console.warn(formattedMessage); | |
return resolve(void 0); | |
}); | |
public override debug: typeof console.debug = async (...args) => | |
new Promise(async (resolve, _) => { | |
const [message, ...rest] = args; | |
const formattedMessage = await this.formatMessage(message); | |
rest.length > 0 | |
? console.debug(formattedMessage, ...rest) | |
: console.debug(formattedMessage); | |
return resolve(void 0); | |
}); | |
public override trace: typeof console.trace = async (...args) => | |
new Promise(async (resolve, _) => { | |
const [message, ...rest] = args; | |
const formattedMessage = await this.formatMessage(message); | |
rest.length > 0 | |
? console.trace(formattedMessage, ...rest) | |
: console.trace(formattedMessage); | |
return resolve(void 0); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment