shimdh
4/21/2014 - 8:01 AM

example source using extendObject.js

example source using extendObject.js

"use strict";

require('./extendObject'); // for __stack, __line, __function

var fs = require('fs');
var winston = require('winston');
var moment = require('moment');
var util = require('util');


module.exports = (function() {
    var logger = new(winston.Logger)({
        transports: [
            new(winston.transports.Console)({
                level: CONFIG.logLevel.console,
                colorize: true,
                timestamp: true
            }),
            new(winston.transports.File)({
                filename: makeLogFile(),
                maxsize: 1024 * 1024 * 100,
                level: CONFIG.logLevel.file,
                timestamp: true
            })
        ]
    });

    // add custom method
    logger.errorEx = function(msg, err) {
        var stack = __stack[1];
        var fileName = stack && stack.getFileName();
        var funcName = stack && stack.getFunctionName();
        var lineNumber = stack && stack.getLineNumber();
        var str = util.format('[%s:%d %s()] : %s', fileName, lineNumber, funcName, msg);
        if (err) {
            if ('string' == typeof err)
                str += ' | err=' + err;
            else
                str += ' | err=' + JSON.stringify(err);
        }
        // call original winston log system.
        return this.error(str);
    };

    return logger;
})();

function makeLogFile() {
    var path = process.cwd();
    if (!fs.existsSync(path + '/log')) {
        fs.mkdir(path + '/log', 755);
    }
    //return (path + '/log/log_' + moment(new Date()).format("YYYY-MM-DD HH:mm:ss") + '.txt');
    return (path + '/log/log_' + moment(new Date()).format("YYYY-MM-DD_HH_mm_ss") + '.txt');
}