remove.js 1.45 KB
const fs = require('fs').promises;
const path = require('path');
const moment = require('moment');
const logger = require('tektrans-logger');

const MODULE_NAME = 'LOGS.REMOVE';
const MAX_OLD_LOG_FILE_D = 14;
const APP_DIRECTORY = path.dirname(require.main.filename);
const LOG_DIRECTORY = `${APP_DIRECTORY}/logs`;

/**
 * remove old log file
 *
 * @param xid
 */
module.exports = async (xid) => {
    try {
        const files = await fs.readdir(LOG_DIRECTORY);
        files.forEach(async (file) => {
            try {
                const filepath = `${LOG_DIRECTORY}/${file}`;
                const stat = await fs.stat(filepath);
                const now = moment();
                const endtime = moment(stat.ctime).add(MAX_OLD_LOG_FILE_D, 'days');
                if (now > endtime) {
                    logger.verbose(`${MODULE_NAME} 7F8B9696: Remove old log file`, {
                        xid,
                        file,
                        ctime: stat.ctime || null,
                        filepath,
                    });

                    await fs.unlink(filepath);
                }
            } catch (e) {
                logger.error(`${MODULE_NAME} 3CD3E8E1: Exception`, {
                    xid,
                    file,
                    eMessage: e.message,
                });
            }
        });
    } catch (e) {
        logger.error(`${MODULE_NAME} A34F605F: Exception`, {
            xid, eMessage: e.message,
        });
    }
};