0

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>
Tony
  • 3,269
  • 1
  • 27
  • 48
  • not with `console.log` [this question](http://stackoverflow.com/questions/21030027/getting-chromes-console-log-to-display-the-line-that-called-a-function) has other options though. – scrappedcola Dec 12 '14 at 18:00
  • I was afraid of that :( thanks for the link ill read it over. – Tony Dec 12 '14 at 18:07
  • @scrappedcola if you want to leave an answer ill tag it as such i got what i needed, unfortunately not as nice as the built in line links but what can you do :/. – Tony Dec 12 '14 at 18:41

2 Answers2

0

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.
XiaoYuze
  • 21
  • 4
  • I was unable to get the correct line number, it was close but not enough. thank you. – Tony Dec 12 '14 at 18:42
  • @Tony I think you can only get the right number by calling the logging function directly, not by calling another function that help you do the logging. But somehow you can do someting to get a new logger that can meet you requirement and then calling it directly, please check my updated answer out to see if this can help. – XiaoYuze Jun 24 '16 at 09:59
0

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]);
Tony
  • 3,269
  • 1
  • 27
  • 48