likes
comments
collection
share

5分钟教你使用 console.log 管理你的输出日志

作者站长头像
站长
· 阅读数 17

前言

在开发过程中,我们经常会使用 console.log 来输出一些信息,以便于我们调试。但是,当我们的项目越来越大,我们的 console.log 也会越来越多,这时候我们就需要对 console.log 进行管理,以便于我们更好的调试。

  • 以埋点为例子,本地开发中,我们一般是通过打印埋点来看是否生效,这时候埋点日志可能跟其它日志混在一起,我们很难找到我们想要的日志,这时候我们就需要对埋点日志进行管理,以便于我们更好的调试。
logN.success("埋点", "page_click_report", {
    eventName: "page_click_report",
    params: {
        user_id: "linwu",
        age: "18",
        height: "171cm",
        sex: "male",
        wx: "linwu-hi"
    }
});

5分钟教你使用 console.log 管理你的输出日志

  • 版本号信息

5分钟教你使用 console.log 管理你的输出日志

  • 打印请求信息

有时候在混合H5开发的时候,接口并不是走XHR而是由客户端提供的JSBridge请求,这时候我们就要对log进行一些处理,以便于我们更好的调试。

5分钟教你使用 console.log 管理你的输出日志

Log函数

直接copy下面的代码到项目中,可以直接使用,童叟无欺啊亲

type Color = 'primary' | 'success' | 'info' | 'warning' | 'danger' | 'error';

const COLORS: Color[] = ['primary', 'success', 'info', 'warning', 'danger', 'error'];

const COLOR_MAP: Record<Color, string> = {
  primary: '#2d8cf0',
  success: '#19be6b',
  info: '#909399',
  warning: '#ff9900',
  danger: '#35495E',
  error:"#FF0000"
};

const getColor = (type: Color) => COLOR_MAP[type];

const createLog = <T extends any[]>(
  fn: (type: Color, ...args: T) => void
): Record<Color, (...args: T) => void> => {
  return COLORS.reduce((logs, type) => {
    logs[type] = (...args: T) => fn(type, ...args);
    return logs;
  }, {} as Record<Color, (...args: T) => void>);
};

const nsLog = (type: Color, ns: string, msg: string, ...args: any[]) => {
  const color = getColor(type);
  console.log(
    `%c ${ns} %c ${msg} %c ${args.length ? '%o' : ''}`,
    `background:${color};border:1px solid ${color}; padding: 1px; border-radius: 4px 0 0 4px; color: #fff;`,
    `border:1px solid ${color}; padding: 1px; border-radius: 0 4px 4px 0; color: ${color};`,
    'background:transparent',
    ...args
  );
};

export const logN = createLog(nsLog);

const sLog = (type: Color, msg: string, ...args: any[]) => {
  const color = getColor(type);
  console.log(
    `%c ${msg} ${args.length ? '%o' : ''}`,
    `color: ${color};`,
    ...args
  );
};

export const logS = createLog(sLog);

const bLog = (type: Color, msg: string, ...args: any[]) => {
  const color = getColor(type);
  console.log(
    `%c ${msg} ${args.length ? '%o' : ''}`,
    `background:${color}; padding: 2px; border-radius: 4px; color: #fff;`,
    ...args
  );
};

 export const logB = createLog(bLog);

示例

小册

整理两本小册,一本是前端面试小册,一本是图解算法,阅读体验都很好,欢迎添加我微信linwu-hi获取

5分钟教你使用 console.log 管理你的输出日志