1 | /** @typedef {"info" | "warning" | "error"} LogLevel */
|
---|
2 |
|
---|
3 | /** @type {LogLevel} */
|
---|
4 | var logLevel = "info";
|
---|
5 |
|
---|
6 | function dummy() {}
|
---|
7 |
|
---|
8 | /**
|
---|
9 | * @param {LogLevel} level log level
|
---|
10 | * @returns {boolean} true, if should log
|
---|
11 | */
|
---|
12 | function shouldLog(level) {
|
---|
13 | var shouldLog =
|
---|
14 | (logLevel === "info" && level === "info") ||
|
---|
15 | (["info", "warning"].indexOf(logLevel) >= 0 && level === "warning") ||
|
---|
16 | (["info", "warning", "error"].indexOf(logLevel) >= 0 && level === "error");
|
---|
17 | return shouldLog;
|
---|
18 | }
|
---|
19 |
|
---|
20 | /**
|
---|
21 | * @param {(msg?: string) => void} logFn log function
|
---|
22 | * @returns {(level: LogLevel, msg?: string) => void} function that logs when log level is sufficient
|
---|
23 | */
|
---|
24 | function logGroup(logFn) {
|
---|
25 | return function (level, msg) {
|
---|
26 | if (shouldLog(level)) {
|
---|
27 | logFn(msg);
|
---|
28 | }
|
---|
29 | };
|
---|
30 | }
|
---|
31 |
|
---|
32 | /**
|
---|
33 | * @param {LogLevel} level log level
|
---|
34 | * @param {string|Error} msg message
|
---|
35 | */
|
---|
36 | module.exports = function (level, msg) {
|
---|
37 | if (shouldLog(level)) {
|
---|
38 | if (level === "info") {
|
---|
39 | console.log(msg);
|
---|
40 | } else if (level === "warning") {
|
---|
41 | console.warn(msg);
|
---|
42 | } else if (level === "error") {
|
---|
43 | console.error(msg);
|
---|
44 | }
|
---|
45 | }
|
---|
46 | };
|
---|
47 |
|
---|
48 | var group = console.group || dummy;
|
---|
49 | var groupCollapsed = console.groupCollapsed || dummy;
|
---|
50 | var groupEnd = console.groupEnd || dummy;
|
---|
51 |
|
---|
52 | module.exports.group = logGroup(group);
|
---|
53 |
|
---|
54 | module.exports.groupCollapsed = logGroup(groupCollapsed);
|
---|
55 |
|
---|
56 | module.exports.groupEnd = logGroup(groupEnd);
|
---|
57 |
|
---|
58 | /**
|
---|
59 | * @param {LogLevel} level log level
|
---|
60 | */
|
---|
61 | module.exports.setLogLevel = function (level) {
|
---|
62 | logLevel = level;
|
---|
63 | };
|
---|
64 |
|
---|
65 | /**
|
---|
66 | * @param {Error} err error
|
---|
67 | * @returns {string} formatted error
|
---|
68 | */
|
---|
69 | module.exports.formatError = function (err) {
|
---|
70 | var message = err.message;
|
---|
71 | var stack = err.stack;
|
---|
72 | if (!stack) {
|
---|
73 | return message;
|
---|
74 | } else if (stack.indexOf(message) < 0) {
|
---|
75 | return message + "\n" + stack;
|
---|
76 | }
|
---|
77 | return stack;
|
---|
78 | };
|
---|