'google apps script: get the name of the function that is currently running
I'm trying to get google apps script to log the current function that is running. I have something similar in python like so:
code_obj = sys._getframe(1).f_code
file = os.path.basename(code_obj.co_filename).split('.')[0]
Def = code_obj.co_name
line = str(sys._getframe(1).f_lineno)
try:
Class = get_class_from_frame(sys._getframe(1)).__name__
except:
Class = ''
return "--> " + file + "." + Class + "()." + Def + "()." + line + " --> " + now() + '\n'
Anybody know how to get the name of the current running function?
Solution 1:[1]
As in plain JavaScript, you can retrieve current function via arguments.callee, and then retrieve Function's property name:
callee
is a property of thearguments
object. It can be used to refer to the currently executing function inside the function body of that function.
function myFunctionName() {
const functionName = arguments.callee.name;
// ...
}
Important note:
Since ES5, arguments.callee
is forbidden in strict mode. This can cause an error in cases where the script is using strict mode behind the scenes (see, for example, this):
TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
I've noticed this happening, for example, when using default parameters or rest parameters.
Unfortunately, there's not an easy alternative to arguments.callee
:
Solution 2:[2]
There's a nice way to get all function names and lines called in google-apps-script using:
(new Error()).stack
Please try:
function test() {
console.log(f_(100));
}
function f_(n) {
console.log(stack2lines_((new Error()).stack))
return n + 1;
}
function stack2lines_(stack) {
var re1 = new RegExp('at ([^ ]+) \\(Code\\:(\\d+).*', 'gm');
var re2 = new RegExp('\\{.*\\}', 'gm');
var result = stack
.replace(re1, '{"$1": $2}')
.match(re2);
return result;
}
The result:
[ '{"f_": 6}', '{"test": 2}' ]
Source:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Iamblichus |
Solution 2 | Max Makhrov |