Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

You actually can get the line number of a caller in JS: https://github.com/eriwen/javascript-stacktrace


You can just parse (new Error).stack:

    var __LINE__ = (new Error).stack.split("\n")[1].match(/:([0-9]+):/)[1];


I do something similar for logging my node apps... in .Net I use reflection for essentially the same.


`(new Error()).stack` is non-standard. But that’s a nice hack, nevertheless.


The underlying construct (console.log processing "%c" and styles) is nonstandard to begin with.


Yes. It will not break, though.

Unless you’re running it on an old IE that doesn’t host the `window.console` object.


Note: that uses arguments.callee, which is disallowed in ES5 strict-mode.


After looking at the code in more depth, I feel I should point out that it looks like `arguments.callee` is only the last-ditch fallback for generating a trace. I see baked-in support for Chrome, IE, FF, Safari, and Opera, and so unless your preferred browser is something else (or you want to target every possible browser) then you could change just a few lines to make it strict mode compliant.


Thanks for these suggestions. You can track progress on this here: https://github.com/adamschwartz/log/issues/1


This will severely degrade performance in almost every scenario. I don't recommend doing it by default, though it is a nice feature to have. Sometimes you want to be able to call console.log a few times per frame in a game without your framerate dropping into the single digits.


Calling `console.log()` in “production mode” is a bad idea, anyway.

Ideally, you’ll want those calls stripped at some point, in your build script.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: