-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.ts
35 lines (31 loc) · 808 Bytes
/
parser.ts
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
import { LogLevel, LogEntry } from "./types.ts";
export function parseLogEntry(
level: LogLevel,
format: string,
outputFormat: string,
...args: unknown[]
): LogEntry {
const variables: any = {};
const message = format.replace(/\{([^{]*?)\}/g, (_, p1: string) => {
const arg = args.shift();
variables[p1] = arg;
return `${arg}` || "";
});
const formattedMessage = outputFormat.replace(
/\{([^{]*?)\}/g,
(_, p1: string) => {
if (p1 === "timestamp") return new Date().toISOString();
if (p1 === "level") return LogLevel[level];
if (p1 === "message") return message;
if (p1 === "params") return JSON.stringify(variables);
return `{${p1}}`;
},
);
return {
level,
format,
message,
formattedMessage,
variables,
};
}