I have a large google app script writing lots of log line to the log explorer. I want to be able to disable or enable logging if needed.
Here's a code that seems to work as expected on a browser.
Here allowlog
is set in code, but it will retrieved from external source. This is not important for the purpose of this post.
The self extracting function overrides console.log
and blocks logging if needed.
let allowLog = false;
function func1(){
console.log("func1 log msg");
}
(function(){
//test log 1
console.log("self extracting");
//keep ref to global console.log
const _consolelog = console.log;
//test log 2 - verify it works
_consolelog("self extracting2");
//override global console.log
console.log = function(val){
if (allowLog){
_consolelog(val);
_consolelog("allowing");
}else{
_consolelog("log disabled");
}
}
})();
This code does not work on google app script, and logs keep on writing.
In app script I can see console.log("self extracting");
and _consolelog("self extracting2");
log messages when module is loaded. However when func1
is called log is written even though allowLog = false
.
_consolelog("allowing");
nor _consolelog("log disabled");
is NOT logged. the global console.log is not overridden.
Why is that, and how (if at all) it is possible to fix it?
The expected log for the above code is (allowLog=false
):
- self extracting
- self extracting2
- log disabled
For the case where allowLog=true
:
- self extracting
- self extracting2
- func1 log msg
- allowing
The first two lines self extracting and self extracting2 should be printed only once, when the anonymous self invoking function is executed. The other should come from the internal function which overides the global one