Custom Node JS logger class with Winston package

Today I would like to share a custom Node JS logger Class using winston package. Let’s take a look.

const winston = require('winston')
nowDate = () => {return new Date(Date.now()).toUTCString()}

class CustomLogger {
  constructor() {
    
    this.logData = null
    const logger = winston.createLogger({
      transports: [
        new winston.transports.Console(),
        new winston.transports.File({
          filename: `./logs/debug.log`
        })
      ],
      format: winston.format.printf((info) => {
        let message = `${nowDate()} | ${info.level.toUpperCase()} | debug.log | ${info.message} | `
        message = info.data ? message + `data:${JSON.stringify(info.data)} | ` : message
        message = this.logData ? message + `logData:${JSON.stringify(this.logData)} | ` : message
        return message
      })
   });
   this.logger = logger
}
setLogData(logData) {
  this.logData = logData
}
async info(message) {
  this.logger.log('info', message);
}
async info(message, data) {
  this.logger.log('info', message, {
    data
  })
}
async debug(message) {
  this.logger.log('debug', message);
}
async debug(message, data) {
  this.logger.log('debug', message, {
    data
  })
}
async error(message) {
  this.logger.log('error', message);
}
async error(message, data) {
  this.logger.log('error', message, {
    data
  })
}
}
module.exports = CustomLogger

The logger class is as above. It is very simple to use. Just call the class and instantiate the class as follows.

const Logger = require('./customLogger')
const logger = new Logger()

This is all for now. Hope you enjoy that.

By Asahi



アプリ関連ニュース

お問い合わせはこちら

お問い合わせ・ご相談はお電話、またはお問い合わせフォームよりお受け付けいたしております。

tel. 06-6454-8833(平日 10:00~17:00)

お問い合わせフォーム