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;
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.
- 79.
- 80.
- 81.
- 82.
- 83.