All files / backend/koa-middleware logger.js

100% Statements 12/12
100% Branches 3/3
100% Functions 4/4
100% Lines 12/12
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 561x 1x                             7x 7x                     49x 1x             7x                   7x 7x 7x   7x       1x  
const logger = require('koa-logger');
const jsonSafeStringify = require('../../utils/jsonSafeStringify');
 
/**
 * This middleware have 2 functions.
 * 1) is to use `koa-logger` for tracking all app activities, and
 * 2) is to provide the app with logging functions like `ctx.logger.info()`
 *
 * @category middleware
 *
 * @param {Object} ctx Koa context
 * @param {Function} next Koa next middleware
 *
 * @return {object} `koa-logger` middleware
 */
function customLogger(ctx, next) {
  let method = '';
  let url = '';
 
  /**
   * Extends the Koa context with `ctx.logger.*` functions that have common logging format
   *
   * @category BackEndUtils
   *
   * @param {String} prefix
   * @return {function}
   */
  function log(prefix = 'INFO') {
    return (message = '', data = {}) => {
      return process.stdout.write(
          `${new Date().toISOString()} ${prefix} - ${method} ${url}` +
          ` - ${message} ${jsonSafeStringify(data)}\n`
      );
    };
  }
 
  ctx.logger = {
    log: log(),
    debug: log('DEBUG'),
    info: log('INFO'),
    warn: log('WARN'),
    warning: log('WARNING'),
    danger: log('DANGER'),
    error: log('ERROR'),
  };
 
  return logger((str, [format, _method, _url]) => {
    method = _method;
    url = _url;
 
    process.stdout.write(`${new Date().toISOString()}${str}\n`);
  })(ctx, next);
}
 
module.exports = customLogger;