December 30, 2023

Log Colorize

Раскрашиваем лог в консоли.

class LogColor {
  static colors = {
    reset: "\x1b[0m",
    bright: "\x1b[1m",
    dim: "\x1b[2m",
    underscore: "\x1b[4m",
    blink: "\x1b[5m",
    reverse: "\x1b[7m",
    hidden: "\x1b[8m",
    black: "\x1b[30m",
    red: "\x1b[31m",
    green: "\x1b[32m",
    yellow: "\x1b[33m",
    blue: "\x1b[34m",
    magenta: "\x1b[35m",
    cyan: "\x1b[36m",
    white: "\x1b[37m"
  };

  static colorize(text, colorName) {
    const color = this.colors[colorName] || this.colors.reset;
    return `${color}${text}${this.colors.reset}`;
  }
}

// Пример использования
console.log(LogColor.colorize('Этот текст будет зеленым', 'green'));
console.log(LogColor.colorize('А этот текст будет красным', 'red'));
console.log(LogColor.colorize('И этот текст будет желтым', 'yellow'));

модуль Colorize.js

class Colorize {
  static colors = {
    reset: "\x1b[0m",
    bright: "\x1b[1m",
    dim: "\x1b[2m",
    underscore: "\x1b[4m",
    blink: "\x1b[5m",
    reverse: "\x1b[7m",
    hidden: "\x1b[8m",
    black: "\x1b[30m",
    red: "\x1b[31m",
    green: "\x1b[32m",
    yellow: "\x1b[33m",
    blue: "\x1b[34m",
    magenta: "\x1b[35m",
    cyan: "\x1b[36m",
    white: "\x1b[37m"
  };


  static log(color, text) {
    return `${color}${text}${Colorize.colors.reset}`;
  }

  static createColorMethod(color) {
    return function (text) {
      return Colorize.log(Colorize.colors[color], text);
    };
  }
}

// Создание методов для каждого цвета
for (const color in Colorize.colors) {
  if (Colorize.colors.hasOwnProperty(color)) {
    Colorize[color] = Colorize.createColorMethod(color);
  }
}

module.exports = Colorize;

Использование

const Colorize = require('./colorize.js');
console.log('Server is running - ' + Colorize.bright(`${host}:${port}`));