logger.js 1.75 KB
"use strict";

const fs = require('fs');
const strftime = require('strftime');
const winston = require('winston');
require('winston-daily-rotate-file');

var loggerTimestamp = function() {
    return strftime('%F %T', new Date());
}

var logger;

function init(_filenamePrefix) {
    //console.trace('Inisialisasi logger');

    const logDirectory = 'logs';
    fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);

    let filenamePrefix;

    if (_filenamePrefix) {
        filenamePrefix = logDirectory + '/' + _filenamePrefix;
    }
    else {
        filenamePrefix = logDirectory + "/log";
    }

    logger = new winston.Logger({
        transports: [
            new (winston.transports.Console)({
                timestamp: function() {
                        return strftime('%F %T', new Date());
                },
                level: 'verbose',
            }),

            new (winston.transports.DailyRotateFile) ({
                name: 'log-file-txt',
                filename: filenamePrefix,
                timestamp: loggerTimestamp,
                formatter: function(options) {
                    return options.timestamp()
                        +' ' + options.level.toUpperCase()
                        +' ' + (undefined !== options.message ? options.message : '')
                        + (options.meta && Object.keys(options.meta).length ? '\n\t' + JSON.stringify(options.meta) : '' );
                },
                level: 'debug',
            }),
        ]
    });

    logger.verbose(__filename + ': initialized');
    return logger;
}

function get() {
    if (!logger) {
        console.trace('Logger uninitialized, aborting process');
        process.exit(1);
    } else {
        return logger;
    }
}

exports.init = init;
exports.get = get;