How can i write a console log wrapper that:
- Keeping the recorded line number and file name of the log statement intact
- Provides access to all log severity methods (error, log, debug, ...) and shows them in the console as they where logged
- does provide some fallback (for example calls the log method when the browser does not support error)
- can be switched off in a central location, so I can switch off logging for production
- does handle the case that no console exists, and does not throw errors
Since logging in Java Script is so inconsistent, there must be some solution. Implementing it myself is a little bit tedious, but there seems to be no good library.
I currently found this logger that provides all the features, but it does mess up the line numbers. http://benalman.com/projects/javascript-debug-console-log/
There is my own log4javascript, which has its own logging console but also provides a wrapper around
console.log
. It fulfils all your criteria except keeping line numbers intact, which is impossible to achieve if you're wrapping calls toconsole.log()
etc. in another function.We had this issue with our log wrapper also and it turns out there is a fantastic, simple workaround using partial function application:
With this, your browser will detect the correct line number and file of the source you wanted to log.