All files / src/utilities/loggers logger.node.js

100% Statements 20/20
100% Branches 6/6
100% Functions 3/3
100% Lines 20/20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59  9x 9x 9x   9x   9x 9x 9x   9x 3x     9x     9x                     9x             9x 2x       9x 2x 2x     9x 2x                   9x  
// Node.js logger utilities using winston
const fs = require('fs');
const path = require('path');
const { createLogger, format, transports } = require('winston');
 
const { combine, label, printf, simple, timestamp } = format;
 
const LOG_LEVEL = process.env.LOG_LEVEL || 'info';
const LOG_FILE = 'app.log';
const LOG_DIR = process.env.LOG_DIR || 'log';
 
if (!fs.existsSync(LOG_DIR)) {
  fs.mkdirSync(LOG_DIR);
}
 
const logLocation = path.join(LOG_DIR, LOG_FILE);
 
// prettier-ignore
const fileTransport = new (transports.File)({
  filename: logLocation,
  handleExceptions: true,
  humanReadableUnhandledException: true,
  json: true,
  level: LOG_LEVEL,
  maxFiles: 1,
  maxsize: 104857600, // 100MB
});
 
// prettier-ignore
const consoleTransport = new (transports.Console)({
  handleExceptions: true,
  humanReadableUnhandledException: true,
  level: LOG_LEVEL,
  timestamp: true,
});
 
const customFormatting = printf(
  data => `${data.timestamp} ${data.level} [${data.label}] ${data.message}`,
);
 
// e.g. outputs 'Article/index.jsx'
const folderAndFilename = name => {
  const fileparts = name.split(path.sep);
  return fileparts.splice(-2).join(path.sep);
};
 
const logger = callingFile =>
  createLogger({
    format: combine(
      label({ label: folderAndFilename(callingFile) }),
      simple(),
      timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
      customFormatting,
    ),
    transports: [fileTransport, consoleTransport],
  });
 
module.exports = logger;