分享: 将代码行数和文件名封装到日志系统,支持winston log4js
发布于 7 年前 作者 danielsss 6237 次浏览 来自 分享

不废话,看代码

Object.defineProperty(global, '__stack', {
    get: function(){
        let orig = Error.prepareStackTrace;
        Error.prepareStackTrace = function(_, stack){ return stack; };
        let err = new Error;
        Error.captureStackTrace(err, arguments.callee);
        let stack = err.stack;
        Error.prepareStackTrace = orig;
        return stack;
    }
});

const wrap = function(level){
    let _type = global.log[level];
    global.log[level] = function(){
        let file = `[File: ${path.basename(__stack[1].getFileName())}]`;
        let line = `[Line: ${__stack[1].getLineNumber()}]`;
        Array.prototype.unshift.call(arguments, file);
        Array.prototype.unshift.call(arguments, line);
        _type.apply(global.log, arguments);
    };
};
_.forEach(['info', 'silly', 'debug','verbose', 'warn', 'error'], wrap);

日志格式如下

Mon Jul 17 2017 10:05:50 GMT+0800 (CST) - info: [Line: 42] [File: www] Http server listening on port 8080
Mon Jul 17 2017 10:05:50 GMT+0800 (CST) - info: [Line: 52] [File: www] Https server listening on port 8443
Mon Jul 17 2017 10:05:50 GMT+0800 (CST) - info: [Line: 43] [File: client.js] Redis cache server is connected with address 192.168.66.145:6379
Mon Jul 17 2017 10:05:50 GMT+0800 (CST) - info: [Line: 43] [File: client.js] Redis logger server is connected with address 192.168.66.145:6379
Mon Jul 17 2017 10:05:50 GMT+0800 (CST) - info: [Line: 198] [File: client.js] Mongodb connected to mongodb://192.168.66.145:27017/cms
Mon Jul 17 2017 10:05:50 GMT+0800 (CST) - info: [Line: 183] [File: client.js] MongoDB db.visitcms.createIndexes note: all indexes already exist
Mon Jul 17 2017 10:05:50 GMT+0800 (CST) - info: [Line: 193] [File: client.js] MongoDB db.downloads.createIndexes note: all indexes already exist
Mon Jul 17 2017 10:05:50 GMT+0800 (CST) - info: [Line: 25] [File: models.js] { '0': 'Executing (default): SELECT 1+1 AS result' }
1 回复

感觉这样使用,在正式环境会有性能问题。

回到顶部