DEV Community

malezjaa
malezjaa

Posted on • Edited on

Good logging library for node.js?

Hi, I recently created a library for logging. I wanted to share it with you and show you how it works.

First you have to install it:

npm install prime-console
Enter fullscreen mode Exit fullscreen mode

Now we can initialize the Logger class.

import { Logger } from 'prime-console';

const logger = new Logger({
   logLevel: 5
});
Enter fullscreen mode Exit fullscreen mode

By deafult, it will only log error messages. To change that set logLevel to 5.

Here you will find all available options:

import { Logger, LoggerOptions } from 'prime-console';

const options: LoggerOptions = {
  config: {
    info: {
      color: "blue",
    },
    error: {
        color: "#e17607",
    },
    warning: {
      color: "yellow",
    },
    debug: {
      color: "magenta",
    },
    verbose: {
      color: "cyan",
    },
    silly: {
      color: "green",
    },
  },
  format: "[%t] %d %m",
  logFile: "./log.txt",
  logLevel: 5,
  logFileFormat: "json",
};

const logger = new Logger(options);
Enter fullscreen mode Exit fullscreen mode
  • format - way of message being displayed
    • %t - type
    • %d - date/time
    • %m - message

CLI

npx prime generate

  • run this to easily generate Logger config

You can save your logs to text file:

import {Logger} from 'prime-console';

const logger = new Logger({logLevel: 5, logFile: 'log.txt'});

logger.info('test file log message');
Enter fullscreen mode Exit fullscreen mode

or save to json

import {Logger} from 'prime-console';

const logger = new Logger({logLevel: 5, logFile: 'log',  logFileFormat: "json"});

logger.info('test file log message');
Enter fullscreen mode Exit fullscreen mode

Don't forget about custom colors and log levels:

const options: LoggerOptions = {
  config: {
    error: {
        color: "#e17607",
    },
  },
  logLevel: 5
}

const log = new Logger(options)

logger.addCustomLevel('custom', 3, 'blue');
logger.custom('test custom message', 'custom');
Enter fullscreen mode Exit fullscreen mode

Clear function:

import {Logger} from 'prime-console';

const logger = new Logger({logLevel: 5});

logger.clear() or logger.clear(true)
Enter fullscreen mode Exit fullscreen mode
  • Clear function will clear the console. If true is provided as first argument, function will also clear the log file.

You can find source code here: https://github.com/malezjaa/prime-console If you want you can give it a star.

Top comments (0)