/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
// registering transport with winston
require('winston-daily-rotate-file');
const winston = require('winston');

/**
 * Instantiates a new winston DailyRotateFile transport and registers an error
 * handler for log files that cannot be accessed. See NODE-266
 * @param {Object} opts
 * @param {string} opts.level
 * @param {string} opts.filename
 * @param {Logger} debugLogger optional debug logger to log
 */
module.exports = function safeDailyRotateFile(opts, debugLogger) {
  try {
    const dailyRotateFile = new winston.transports.DailyRotateFile(opts);

    dailyRotateFile.logStream.on('error', (err) => {
      if (debugLogger) {
        debugLogger.warn(
          `There was a problem opening or writing to the log file at ${err.path}. Continuing without security logging.`
        );
      }
    });

    return dailyRotateFile;
  } catch (err) {
    // If we're unable to instantiate a DailyRotateFile transport, we need to
    // provide something else so that winston doesn't get upset.
    return new winston.transports.Console({ silent: true });
  }
};
