问题
I created a wrapper for console logging. I have been unable to get it to display the logged line number that the wrapper function is called from. I have looked at other posts to handle this but I cannot seem to get what they mentioned. They were basically binding the console.log to the external function but I need to do other work inside before its used.
Is it possible with my setup?
Error Free JsFiddle
var logger = (function (window, console) {
// logger object
function logger() {
// use to initialize the logger
function init() {
fixConsole();
}
// fix missing console
function fixConsole() {
var logmethod;
var noop = function () { };
var logmethods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = logmethods.length;
console = (window.console = window.console || {});
while (length--) {
logmethod = logmethods[length];
// Only stub undefined methods.
if (!console[logmethod]) {
console[logmethod] = noop;
}
}
}
// initializing the logger
init();
}
// logging methods
logger.prototype = {
info: function (msg, title) {
if (title)
console.log(title + ": " + msg);
else
console.log(msg);
}
}
// create logger
function _create() {
// create logger
var log = new logger();
// return logger
return log;
}
// exposed functions
return {
create: _create
}
})(window, console);
var log = logger.create();
log.info('Hello, I am trying to get the logger to log under the line number info is used on.');
log.info('For instance I want line number 75 to show.');
<h1> Press F12 and look at the console to see</h1>
回答1:
To be precise on what I did to get the error number including the regex needed to grab it.
var err = getErrorObject();
var caller_line = err.stack.split("\n")[4];
var index = caller_line.indexOf("at ");
var clean = caller_line.slice(index+2, caller_line.length);
var number = clean.match(/(?!:)\d*(?=\:)/g);
console.log(number[0]);
回答2:
I'm not sure what you want.
But if you want to get the correct line number where it is called from, maybe you need to trace the stack.
Try the console.trace() function.
// updated at 2016-6-24
I've been faced in the same problem lately, and I find out the only way you can get the right line number is actually calling the logging function at the right place, you can never get the right number by calling another function that help you to do the logging.
There is nothing you can do in that way, but somehow you can do something to get a new logger and then call it directly (Like what you said, using .bind
).
This is what we do in our project, in our case, we need to wrap many informations into all our console.log, and all that informations can only access by the req
object. (In Express)
So we write a middleware to help.
export default function logFactory() {
return (req, res, next) => {
function getLogger(type = 'log', ...args) {
let user = 'unknown';
try {
user = req.session.cas.user;
} catch (e) {
}
if (!console[type]) {
console.error('invalid console type', type);
}
return console[type].bind(console[type], `${req.sn}|${user}|${req.ip}|`, ...args);
}
req.getLogger = getLogger;
req.log = {
debug: getLogger('log'),
info: getLogger('log'),
log: getLogger('log'),
warn: getLogger('warn'),
error: getLogger('error')
};
}
}
Then we can do console.log with all the information we need and getting the correct line number by calling req.log.info('Any business infos here')
.
And this is what we get in out log file by using winston.
2016-06-24 17:47:52|4497|DEBUG|RequestUtils.js:256|0e84f1c3-d5b7-4578-9b83-f03fe9951fb1| unknown| 10.240.138.19| Receiving response from POST /statics/add_pv_uv?portal_auth_key=af27c0bc-cc04-4821-a4de-cbb93c0ed19f 200 60ms.
来源:https://stackoverflow.com/questions/27449382/get-console-wrapper-to-log-message-on-correct-line