如何在函数外部收集console.log的字符串

新手上路,请多包涵

有一个公共模块是共用的,所以尽量不要改动里面的代码,或是少量改动。
目的是在外部收集console日志

//公共模块common.js
class A {
    constructor() {
        console.log("balabala");
    }
    function test() {
        console.error("abccbabab");
    }
    //还有N个一堆方法
}



//后端文件server.js
let a = new A();
//在不改变或少量改动class A情况下,收集到console.log的字符串。
阅读 2.1k
4 个回答

可以重写console.log, console.error,如:

[
    'log',
    'error'
].forEach(key => {
    const fn = console[key].bind(console);
    console[key] = (...args) => {        
        fn(' - before console'); // 自定义行为
        fn(...args); // 原始行为
    }
})

console.error 这些方法自定义一份,把函数体内的打印方法换成自定义的打印方法

重新自定义,但是不太好,
例如:

const log = console.log
// 1:
window.console.log = (...rest) => {
  log('catch1')
  log(...rest)
}
// 2:
Object.defineProperty(console, 'log', {
  get() {
    log('catch2')
    return log;
  }
})

或者用代理,但是用代理,你就需要改class A,因为Proxy是返回一个新的代理对象,其实跟直接用customConsole.log没啥区别,最好其实是自己封装一个Logger,专门记录日志。不太清楚你要这么做的原因

const customConsole: {
  [key: string]: (args:unknown[]) => void
} = {}
const originConsoleProperty = Object.getOwnPropertyNames(console);
originConsoleProperty.forEach(key => {   
    customConsole[key] = function mutator (values) {
        // ... 
    }
});
// 代理
const consoleProxy = new Proxy(console, {    
    get (target, key) {        
        const handlers = customConsole.hasOwnProperty(key) ? customConsole : target;
        return Reflect.get(handlers, key);
}})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题