Skip to content

浏览器彩色日志打印器

这两天队友在做一个 uni-app 项目,交接的时候发现他是用浏览器调试的,而我写的代码用了 log4js,浏览器不能使用这个 npm 包,于是我决定给他写一个浏览器彩色日志打印器。

核心原理

是利用浏览器的console.log方法,通过 css 样式来实现彩色打印。

eg:

js
console.log(
  "%c%s",
  "color:#17a8cd;background-color:#d4f5ff;",
  "这是一条debug日志"
);

代码

可以直接复制,粘贴到浏览器控制台中

js
class Logger {
  /**
   * @param {string} level
   */
  set level(level) {
    if (["debug", "info", "warn", "error"].indexOf(level) == -1) {
      throw new Error("level must be debug | info | warn | error");
    }
    this._level = level;
    this._levelnum = ["debug", "info", "warn", "error"].indexOf(level);
  }
  constructor(name = "log", level = "debug") {
    this._level = "debug"; // debug | info | warn | error
    this._levelnum = 0;
    this._name = name;
    this.level = level;
    this.color = this.stringToColor(name);
  }
  debug(...msg) {
    if (this._levelnum > 0) return;
    let css = "color:#17a8cd;background-color:#d4f5ff;";
    console.log(
      "%c%s",
      css,
      `[${this.getTimestamp()}] [DEBUG] [${this._name}] - `,
      ...msg
    );
  }
  info(...msg) {
    if (this._levelnum > 1) return;
    let css = "color:#008a15;background-color:#e6ffe9;";
    console.log(
      "%c%s",
      css,
      `[${this.getTimestamp()}] [INFO] [${this._name}] - `,
      ...msg
    );
  }
  warn(...msg) {
    if (this._levelnum > 2) return;
    let css = "color:#e88f21;background-color:#fffbe6;";
    console.log(
      "%c%s",
      css,
      `[${this.getTimestamp()}] [WARN] [${this._name}] - `,
      ...msg
    );
  }
  error(...msg) {
    if (this._levelnum > 3) return;
    let css = "color:#ff0000;background-color:#fff0f0;";
    console.log(
      "%c%s",
      css,
      `[${this.getTimestamp()}] [ERROR] [${this._name}] - `,
      ...msg
    );
  }
  getTimestamp() {
    return new Date(new Date().valueOf() + 1000 * 60 * 60 * 8).toISOString();
  }
  log(...msg) {
    console.log(
      "%c%s",
      `color:${this.color};`,
      `[${this.getTimestamp()}] [LOG] [${this._name}] - `,
      ...msg
    );
  }
  // 将任意字符串转换为颜色值
  stringToColor(str) {
    var hash = 0;
    for (var i = 0; i < str.length; i++) {
      hash = str.charCodeAt(i) + ((hash << 5) - hash);
    }
    var color = "#";
    for (var i = 0; i < 3; i++) {
      var value = (hash >> (i * 8)) & 0xff;
      color += ("00" + value.toString(16)).substr(-2);
    }
    return color;
  }
}

have a try

你可以按 F12 打开浏览器控制台试一下

js
let log = new Logger("test", "debug");
log.debug("这是一条debug日志");
log.info("这是一条info日志");
log.warn("这是一条warn日志");
log.error("这是一条error日志");
log.log("这是一条log日志,颜色是根据名称自动生成的");

更新

2023-9-10

将项目发布为 npm 包,项目地址:opchatjs-webLogger

参考资料

Copyright © 2022 田园幻想乡 浙ICP备2021038778号-1