OJN*_*Sim 3 javascript debugging google-apps-script console.log
我有一个大型谷歌应用程序脚本,将大量日志行写入日志资源管理器。我希望能够根据需要禁用或启用日志记录。
下面的代码似乎在浏览器上按预期工作。这里allowlog是在代码中设置的,但它将从外部源检索。这对于本文的目的来说并不重要。
如果需要,自解压功能会覆盖console.log并阻止日志记录。
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");
}
}
})();
Run Code Online (Sandbox Code Playgroud)
此代码不适用于谷歌应用程序脚本,并且日志继续写入。
在应用程序脚本中,我可以 在加载模块时查看console.log("self extracting");并 记录消息。_consolelog("self extracting2");然而,当func1调用日志时,即使allowLog = false.
_consolelog("allowing");也_consolelog("log disabled");没有记录。全局console.log不会被覆盖。
这是为什么,以及如何(如果有的话)可以修复它?
上述代码的预期日志为 ( allowLog=false):
对于以下情况allowLog=true:
当执行匿名自调用函数时,前两行self extracting和self extracting2应该只打印一次。另一个应该来自内部函数,它凌驾于全局函数之上
这是因为log的属性console不是writable。您可以使用 来检查Object.getOwnPropertyDescriptors。然而,它仍然是configurable。因此,您可以delete为该log属性设置一个新值。
let allowLog = false;
(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(Object.getOwnPropertyDescriptors(console));
/*{ toString:
{ value: [Function],
writable: true,
enumerable: true,
configurable: true },
time:
{ value: [Function],
writable: true,
enumerable: true,
configurable: true },
timeEnd:
{ value: [Function],
writable: true,
enumerable: true,
configurable: true },
error:
{ value: [Function],
writable: false,
enumerable: true,
configurable: true },
info:
{ value: [Function],
writable: false,
enumerable: true,
configurable: true },
log:
{ value: [Function],
writable: false,
enumerable: true,
configurable: true },
warn:
{ value: [Function],
writable: false,
enumerable: true,
configurable: true } }*/
delete console.log;
console.log = function (val){
if (allowLog){
_consolelog(val);
_consolelog("allowing");
}else{
_consolelog("log disabled");
}
}
})();
function func1(){
console.log("func1 log msg");
}
Run Code Online (Sandbox Code Playgroud)