如何扩展可以接受args的console.log 更新:堆栈跟踪

问题描述

我一直致力于扩展 console.log 以制作一个色彩丰富的保持堆栈跟踪它被调用的位置。我尝试了一些解决方案,但最终达到了这一点:

export const colorizedLog = (
  text: string,status: keyof typeof ColorStatus = "dark",...args: any
) =>
  console.log.bind(
    console,`%c ${text}`,`font-weight:bold; color: ${ColorStatus[status]}`,...args
  );

有了这个小binding,我们将能够保留堆栈跟踪,但这里的问题是我们必须在最后使用一个恼人的额外(),因为返回值是函数本身是 bind 的结果:

 colorizedLog(
    "Title:","info","This is a working example")();

我阅读过的其他主要资源如下:

  1. Extending console.log
  2. Macro using babel- kent.c dodds
  3. Webpack Define plugin

const colorizedLog = (text,color= "#40a7e3",...args) =>
  console.log.bind(
    console,`font-weight:bold; color:${color}`,...args
  );
colorizedLog("Title:","#40a7e3","This is a working example")();

更新:堆栈跟踪

useAppVersion.ts

enter image description here

App.vue

enter image description here

Chrome 控制台

enter image description here

解决方法

您可以立即调用它:

const colorizedLog = (text,color= "#40a7e3",...args) =>
  console.log.bind(
    console,`%c ${text}`,`font-weight:bold; color:${color}`,...args
  )();

colorizedLog("Title:","#40a7e3","This is a working example");
,

如果您不介意添加另一个对该堆栈跟踪的调用,您可以将其包装在另一个隐藏额外 () 的函数中:

const rawColorizedLog = (
  text: string,status: keyof typeof ColorStatus = "dark",...args: any
) =>
  console.log.bind(
    console,`font-weight:bold; color: ${ColorStatus[status]}`,...args
  );
export const colorizedLog = (...args: any) => rawColorizedLog(...args)();

然后你可以只调用 colorizedLog(...whatever) 但你会在堆栈中额外调用 rawColorizedLog,但我相信你可以想出一个聪明的名字来覆盖 rawColorizedLog用更酷的东西打电话给额外的电话;)