-
Notifications
You must be signed in to change notification settings - Fork 0
/
ratlog.ts
99 lines (85 loc) · 2.72 KB
/
ratlog.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
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import {
escape,
escapeField,
escapeMessage,
escapeTag,
unescape,
unescapeField,
unescapeMessage,
unescapeTag,
} from "./stringmanip.ts";
/**
* An object that either is a string, or reveals a toString() function.
*
* Utility type, used to make the Ratlog API more flexible.
*/
export type Stringable = string | { toString: () => string };
/**
* The base Ratlog data type. All logs are serialized from and parsed to objects of this type.
*/
export interface RatlogData {
message: Stringable;
tags?: Stringable[];
fields?: Record<string, Stringable | null>;
}
export default class Ratlog {
/**
* Take a 'line' of Ratlog data and format it for output.
* @param data the log line to format
*/
static format(data: RatlogData): string {
const tagString = data.tags?.length ?? 0 > 0
? `[${
(data.tags ?? [])
.map((tag) => escapeTag(tag.toString()))
.join("|")
}] `
: ``;
const messageString = escapeMessage(data.message.toString() ?? "");
const fieldString = Object.entries(data.fields ?? {})
.map((entry) =>
entry.map((subentry) =>
subentry != null ? escapeField(subentry.toString()) : subentry
)
)
.map((entry) => `${entry[0]}${entry[1] != null ? `: ${entry[1]}` : ``}`)
.reduce((prev, cur) => `${prev} | ${cur}`, "");
return escape("\n")(tagString + messageString + fieldString) + "\n";
}
/**
* Take a string and parse it.
*
* Known to work on standards-compliant Ratlog formatter output. Not guaranteed to work with log data that doesn't meet the spec.
*
* @param logline a line of text to parse as Ratlog data
*/
static parse(logline: string): RatlogData {
const data: Partial<RatlogData> = {};
logline = logline.replace(/\n$/, ""); // Trim off the newline at the end
logline = unescape("\n")(logline);
const tagSection = logline.match(/^\[(.*(?<!\\))\] ?/);
if (tagSection) {
data.tags = tagSection[1].split(/(?<!\\)\|/g).map(unescapeTag);
logline = logline.substring(tagSection[0].length);
}
const messageSection = logline.match(/.*?(?= \|)/);
const messageString = messageSection ? messageSection[0] : logline;
logline = logline.substring(messageString.length);
data.message = unescapeMessage(messageString);
if (logline.length > 0) {
data.fields = logline
.split(/ (?<!\\)\| /g)
.slice(1)
.reduce((fields: RatlogData["fields"], elem) => {
const parts = elem.split(/(?<!\\): /);
return {
...fields,
[unescapeField(parts[0])]: parts[1]
? unescapeField(parts[1])
: null,
};
}, {});
}
return data as RatlogData;
}
}