If you are using the Logger extensively, it’s sometimes hard to track where the log message is coming from. It would be useful to display line number, file name and function that provoked the log.

Here’s how

First we create a function that throws a deliberate error, then analyzes the call stack of that error to see where it was called from.

Here it is.

By default it will return the location from where it was called, so this –

logs this

Reporting a different stack level

Imagine you have some shared function that’s called from multiple functions, and you have a Logger.log() in your shared function. The example above will show location information about the shared function, but what you really want to log is where shared was called from (and maybe even higher up than that). You can do this by passing a stack level to whereAmI() and it will report back up the call stack as required.

this

will give this

pre class=”lang:sh decode:true ” > my logged message <{"caller":"shared","line":"107","file":"Code"}

whereas running test4 & test5 – with a stack level of 2 passed to whereAmI(2), will give location information about who is calling shared().

Gives this

Getting the whole stack

You can also get the whole stack by passing level 0 – so this

will return this when called from test4.

This function is part of the Useful stuff library

Known issues

if you use this type of structure

then call it like this

The caller is not included in the stack.

Happy logging.

For more like this see Google Apps Scripts Snippets
For help and more information join our forum, follow the blog, follow me on twitter