logger.js 1.35 KB
var strftime = require('strftime');
var winston = require('winston');
var fs = require('fs');

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

function start(options) {
    var logDir = __dirname + '/logs'

    var logLevel = 'debug';
    if (options && options.logLevel) {
        logLevel = options.logLevel;
    }

    if (!fs.existsSync(logDir)) {
        fs.mkdirSync(logDir);
    }

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

            new(require('winston-daily-rotate-file')) ({
                name: './log-file-txt',
                filename: logDir + '/log.txt',
                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: logLevel,
            }),
        ]
    });

    return logger;
}

exports.start = start;