Created
January 15, 2025 09:46
-
-
Save Salemsky/04a01cb36a14d16c1d1cc9776111a88d to your computer and use it in GitHub Desktop.
logger in node(v22+)
This file contains hidden or 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
import { styleText } from 'node:util'; | |
/** @typedef {Extract<keyof typeof console, 'error' | 'info' | 'log' | 'warn'>} LogLevel */ | |
/** @typedef {Parameters<typeof styleText>[0]} Format */ | |
/** @type {Record<LogLevel, Format>} */ | |
const LOG_COLORS = { | |
error: 'red', | |
info: 'cyan', | |
log: 'reset', | |
warn: 'yellow', | |
}; | |
/** | |
* Logs a message to the console with a specified type and optional formatting. | |
* @param {LogLevel} type The type of log message. | |
* @param {Array<[string, Format?]>} args A tuple containing the text to be written to the log and an optional format string. | |
* @returns {void} | |
* @example | |
* ``` | |
* logger('error', ['error', 'green'], ['error', ['underline', 'blue']]); | |
* ``` | |
* | |
*/ | |
export function logger(type, ...args) { | |
let msg = ''; | |
for (const [text, format] of args) { | |
const logFormat = format && format.length > 0 ? format : LOG_COLORS[type]; | |
msg += (msg && ' ') + styleText(logFormat, text); | |
} | |
console[type](msg); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment