Logger Setup with Winston

A simple setup with winston logger:

const { createLogger, format, transports } = require('winston')
require('winston-daily-rotate-file')

module.exports = (fileName = 'application') => {
  const fileLogTransport = new transports.DailyRotateFile({
    filename: `logs/${fileName}-%DATE%.log`,
    datePattern: 'YYYY-MM-DD',
    zippedArchive: true,
    maxSize: '20m',
    maxFiles: '30d'
  })

  const consoleTransport = new transports.Console({
    level: process.env.LOG_LEVEL,
    handleExceptions: false,
    json: false,
    colorize: true,
    format: format.printf(i => `${i.message}`)
  })

  const logger = createLogger({
    level: 'info',
    format: format.combine(
      format.timestamp({
        format: 'YYYY-MM-DD HH:mm:ss'
      }),
      format.errors({ stack: true }),
      format.splat(),
      format.json()
    ),
    defaultMeta: { service: 'shopify-app' },

    transports: [consoleTransport]
  })

  if (process.env.NODE_ENV === 'development') {
    logger.add(fileLogTransport)
  }

  return logger()
}
Share this article

Similar Posts