Re:Console.log with style
by windsurfer on Friday April 12, 2013 @04:16PM
(#5540738)
You actually can get the line number of a caller in JS: https://github.com/eriwen/javascript-stacktrace
[ Parent
| on HN ]
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.
Re:Console.log with style
by cristiantincu on Friday April 12, 2013 @05:52PM
(#5541287)
`(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.
Re:Console.log with style
by cristiantincu on Friday April 12, 2013 @06:08PM
(#5541374)
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.
Re:Console.log with style
by afschwartz on Friday April 12, 2013 @04:23PM
(#5540779)
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.
Re:Console.log with style
by cristiantincu on Friday April 12, 2013 @05:42PM
(#5541239)
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.