Skip to content

Instantly share code, notes, and snippets.

@Salemsky
Created January 15, 2025 09:46
Show Gist options
  • Save Salemsky/04a01cb36a14d16c1d1cc9776111a88d to your computer and use it in GitHub Desktop.
Save Salemsky/04a01cb36a14d16c1d1cc9776111a88d to your computer and use it in GitHub Desktop.
logger in node(v22+)
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