Skip to content

logger

javascript
export class Logger {
  constructor(tag = "") {
    this.tags = [];
    this.tags = this.tags.concat(tag);
    this.isDev = process.env.NODE_ENV === "development";
  }
  log(...arg) {
    let tags = this.genTags();
    this.isDev && console.log(`[info]${tags} : `, ...arg);
  }
  error(...arg) {
    let tags = this.genTags();
    console.error(`[error]${tags} : `, ...arg);
  }
  warn(...arg) {
    let tags = this.genTags();
    this.isDev && console.warn(`[warn]${tags} : `, ...arg);
  }
  genTags() {
    let tags = "";
    for (const tag of this.tags) {
      tag && (tags += `[${tag}]`);
    }
    return tags;
  }
  addTag(tag = "") {
    this.tags = this.tags.concat(tag);
  }
}
/**
 * @description: 日志 支持链式调用例如 logger("tag1")("tag2")("tag3").log("info") 和 logger(["tag1","tag2"]).log("info")
 * @param {*} tag  [tag1][tag2]
 * @return {*} 返回 函数
 */
export default function logger(tag) {
  let log = new Logger(tag);
  function fn(tag = "") {
    log.addTag(tag);
    return fn;
  }
  fn.log = log.log.bind(log);
  fn.error = log.error.bind(log);
  fn.warn = log.warn.bind(log);
  return fn;
}

使用

javascript
import logger from "./logger";
logger("test").log(`test`);