const os = require('os');
const winston = require('winston');

const HOST_NAME = os.hostname();

const transportConsole = new winston.transports.Console({
  level: 'debug',
  handleExceptions: true,
  humanReadableUnhandledException: true,
  colorize: true
});

function censorMetaData(level, msg, meta) {
  if (meta && meta.creditCard) {
    const suffix = meta.creditCard.toString().substr(-4);
    meta.creditCard = ('*').repeat(meta.creditCard.length-4) + suffix;
  }

  if (meta && meta.password) {
    meta.password === '********';
  }

  return meta;
}


function includeServerData(level, msg, meta) {
  if(meta)
    meta.host = HOST_NAME;
  return meta;
}

const logger = new winston.Logger({
  transports: [
    transportConsole
  ],
  rewriters: [censorMetaData, includeServerData],
  exitOnError: false
});

module.exports = logger;
module.exports.stream = {
  write: (message, encoding) => {
    logger.info(message);
  }
};
