sprinklers3/common/logger.ts

113 lines
2.8 KiB
TypeScript
Raw Normal View History

2017-09-27 19:20:50 -06:00
import * as pino from "pino";
2017-09-30 13:07:38 -06:00
type Level = "default" | "60" | "50" | "40" | "30" | "20" | "10";
2017-09-30 11:04:25 -06:00
2017-09-30 13:07:38 -06:00
const levels: {[level in Level]: string } = {
2017-09-30 11:04:25 -06:00
default: "USERLVL",
60: "FATAL",
50: "ERROR",
40: "WARN",
30: "INFO",
20: "DEBUG",
10: "TRACE",
};
2017-09-30 13:07:38 -06:00
const levelColors: {[level in Level]: string } = {
2017-09-30 11:04:25 -06:00
default: "text-decoration: underline; color: #000000;",
60: "text-decoration: underline; background-color: #FF0000;",
50: "text-decoration: underline; color: #FF0000;",
40: "text-decoration: underline; color: #FFFF00;",
30: "text-decoration: underline; color: #00FF00;",
20: "text-decoration: underline; color: #0000FF;",
10: "text-decoration: underline; color: #AAAAAA;",
};
interface ColoredString {
str: string;
args: any[];
}
function makeColored(str: string = ""): ColoredString {
return { str, args: [] };
}
function concatColored(...coloredStrings: ColoredString[]): ColoredString {
return coloredStrings.reduce((prev, cur) => ({
str: prev.str + cur.str,
args: prev.args.concat(cur.args),
}), makeColored());
}
const standardKeys = ["pid", "hostname", "name", "level", "time", "v", "source", "msg"];
2017-09-30 13:07:38 -06:00
function write(value: any) {
2017-09-30 11:04:25 -06:00
let line = concatColored(
// makeColored(formatTime(value, " ")),
formatSource(value),
formatLevel(value),
makeColored(": "),
);
if (value.msg) {
line = concatColored(line, {
str: "%c" + value.msg, args: ["color: #00FFFF"],
});
}
2017-09-30 13:07:38 -06:00
const args = [line.str].concat(line.args)
.concat([
(value.type === "Error") ? value.stack : filter(value),
]);
2017-09-30 11:04:25 -06:00
let fn;
if (value.level >= 50) {
fn = console.error;
} else if (value.level >= 40) {
fn = console.warn;
} else {
fn = console.log;
}
fn.apply(null, args);
}
function filter(value: any) {
const keys = Object.keys(value);
const result: any = {};
for (const key of keys) {
if (standardKeys.indexOf(key) < 0) {
result[key] = value[key];
}
}
return result;
}
function formatSource(value: any): { str: string, args: any[] } {
if (value.source) {
return { str: "%c(" + value.source + ") ", args: ["color: #FF00FF"] };
} else {
return { str: "", args: [] };
}
}
function formatLevel(value: any): ColoredString {
const level = value.level as Level;
2017-09-30 13:07:38 -06:00
if (levelColors.hasOwnProperty(level)) {
2017-09-30 11:04:25 -06:00
return {
str: "%c" + levels[level] + "%c",
args: [levelColors[level], ""],
};
} else {
return {
str: levels.default,
args: [levelColors.default],
};
}
}
2017-10-09 08:09:08 -06:00
const logger: pino.Logger = pino({
2017-09-30 13:07:38 -06:00
browser: { write },
2017-09-30 11:04:25 -06:00
level: "trace",
});
2017-09-27 19:20:50 -06:00
export default logger;