@logtape/logtape 0.1.0-dev.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +18 -0
  3. package/esm/_dnt.shims.js +61 -0
  4. package/esm/config.js +108 -0
  5. package/esm/filter.js +42 -0
  6. package/esm/formatter.js +85 -0
  7. package/esm/logger.js +285 -0
  8. package/esm/mod.js +5 -0
  9. package/esm/package.json +3 -0
  10. package/esm/record.js +1 -0
  11. package/esm/sink.js +59 -0
  12. package/package.json +44 -0
  13. package/script/_dnt.shims.js +65 -0
  14. package/script/config.js +114 -0
  15. package/script/filter.js +47 -0
  16. package/script/formatter.js +90 -0
  17. package/script/logger.js +292 -0
  18. package/script/mod.js +15 -0
  19. package/script/package.json +3 -0
  20. package/script/record.js +2 -0
  21. package/script/sink.js +64 -0
  22. package/types/_dnt.shims.d.ts +10 -0
  23. package/types/_dnt.shims.d.ts.map +1 -0
  24. package/types/_dnt.test_shims.d.ts.map +1 -0
  25. package/types/config.d.ts +101 -0
  26. package/types/config.d.ts.map +1 -0
  27. package/types/config.test.d.ts.map +1 -0
  28. package/types/deps/jsr.io/@std/assert/0.222.1/_constants.d.ts.map +1 -0
  29. package/types/deps/jsr.io/@std/assert/0.222.1/_diff.d.ts.map +1 -0
  30. package/types/deps/jsr.io/@std/assert/0.222.1/_format.d.ts.map +1 -0
  31. package/types/deps/jsr.io/@std/assert/0.222.1/assert.d.ts.map +1 -0
  32. package/types/deps/jsr.io/@std/assert/0.222.1/assert_equals.d.ts.map +1 -0
  33. package/types/deps/jsr.io/@std/assert/0.222.1/assert_false.d.ts.map +1 -0
  34. package/types/deps/jsr.io/@std/assert/0.222.1/assert_greater_or_equal.d.ts.map +1 -0
  35. package/types/deps/jsr.io/@std/assert/0.222.1/assert_is_error.d.ts.map +1 -0
  36. package/types/deps/jsr.io/@std/assert/0.222.1/assert_less_or_equal.d.ts.map +1 -0
  37. package/types/deps/jsr.io/@std/assert/0.222.1/assert_strict_equals.d.ts.map +1 -0
  38. package/types/deps/jsr.io/@std/assert/0.222.1/assert_throws.d.ts.map +1 -0
  39. package/types/deps/jsr.io/@std/assert/0.222.1/assertion_error.d.ts.map +1 -0
  40. package/types/deps/jsr.io/@std/assert/0.222.1/equal.d.ts.map +1 -0
  41. package/types/deps/jsr.io/@std/async/0.222.1/delay.d.ts.map +1 -0
  42. package/types/deps/jsr.io/@std/fmt/0.222.1/colors.d.ts.map +1 -0
  43. package/types/filter.d.ts +30 -0
  44. package/types/filter.d.ts.map +1 -0
  45. package/types/filter.test.d.ts.map +1 -0
  46. package/types/fixtures.d.ts.map +1 -0
  47. package/types/formatter.d.ts +38 -0
  48. package/types/formatter.d.ts.map +1 -0
  49. package/types/formatter.test.d.ts.map +1 -0
  50. package/types/logger.d.ts +363 -0
  51. package/types/logger.d.ts.map +1 -0
  52. package/types/logger.test.d.ts.map +1 -0
  53. package/types/mod.d.ts +7 -0
  54. package/types/mod.d.ts.map +1 -0
  55. package/types/record.d.ts +33 -0
  56. package/types/record.d.ts.map +1 -0
  57. package/types/sink.d.ts +55 -0
  58. package/types/sink.d.ts.map +1 -0
  59. package/types/sink.test.d.ts.map +1 -0
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright 2024 Hong Minhee
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,18 @@
1
+ <!-- deno-fmt-ignore-file -->
2
+
3
+ LogTape
4
+ =======
5
+
6
+ [![GitHub Actions][GitHub Actions badge]][GitHub Actions]
7
+ [![Codecov][Codecov badge]][Codecov]
8
+
9
+ LogTape is a simple logging library for Deno/Node.js/Bun/browsers. It is
10
+ designed to be used for both applications and libraries.
11
+
12
+ Currently, LogTape provides only few sinks, but you can easily add your own
13
+ sinks.
14
+
15
+ [GitHub Actions]: https://github.com/dahlia/logtape/actions/workflows/main.yaml
16
+ [GitHub Actions badge]: https://github.com/dahlia/logtape/actions/workflows/main.yaml/badge.svg
17
+ [Codecov]: https://codecov.io/gh/dahlia/logtape
18
+ [Codecov badge]: https://codecov.io/gh/dahlia/logtape/graph/badge.svg?token=yOejfcuX7r
@@ -0,0 +1,61 @@
1
+ import { WritableStream } from "node:stream/web";
2
+ export { WritableStream } from "node:stream/web";
3
+ const dntGlobals = {
4
+ WritableStream,
5
+ };
6
+ export const dntGlobalThis = createMergeProxy(globalThis, dntGlobals);
7
+ function createMergeProxy(baseObj, extObj) {
8
+ return new Proxy(baseObj, {
9
+ get(_target, prop, _receiver) {
10
+ if (prop in extObj) {
11
+ return extObj[prop];
12
+ }
13
+ else {
14
+ return baseObj[prop];
15
+ }
16
+ },
17
+ set(_target, prop, value) {
18
+ if (prop in extObj) {
19
+ delete extObj[prop];
20
+ }
21
+ baseObj[prop] = value;
22
+ return true;
23
+ },
24
+ deleteProperty(_target, prop) {
25
+ let success = false;
26
+ if (prop in extObj) {
27
+ delete extObj[prop];
28
+ success = true;
29
+ }
30
+ if (prop in baseObj) {
31
+ delete baseObj[prop];
32
+ success = true;
33
+ }
34
+ return success;
35
+ },
36
+ ownKeys(_target) {
37
+ const baseKeys = Reflect.ownKeys(baseObj);
38
+ const extKeys = Reflect.ownKeys(extObj);
39
+ const extKeysSet = new Set(extKeys);
40
+ return [...baseKeys.filter((k) => !extKeysSet.has(k)), ...extKeys];
41
+ },
42
+ defineProperty(_target, prop, desc) {
43
+ if (prop in extObj) {
44
+ delete extObj[prop];
45
+ }
46
+ Reflect.defineProperty(baseObj, prop, desc);
47
+ return true;
48
+ },
49
+ getOwnPropertyDescriptor(_target, prop) {
50
+ if (prop in extObj) {
51
+ return Reflect.getOwnPropertyDescriptor(extObj, prop);
52
+ }
53
+ else {
54
+ return Reflect.getOwnPropertyDescriptor(baseObj, prop);
55
+ }
56
+ },
57
+ has(_target, prop) {
58
+ return prop in extObj || prop in baseObj;
59
+ },
60
+ });
61
+ }
package/esm/config.js ADDED
@@ -0,0 +1,108 @@
1
+ import { toFilter } from "./filter.js";
2
+ import { LoggerImpl } from "./logger.js";
3
+ import { getConsoleSink } from "./sink.js";
4
+ let configured = false;
5
+ /**
6
+ * Configure the loggers with the specified configuration.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * configure({
11
+ * sinks: {
12
+ * console: getConsoleSink(),
13
+ * },
14
+ * filters: {
15
+ * slow: (log) =>
16
+ * "duration" in log.properties &&
17
+ * log.properties.duration as number > 1000,
18
+ * },
19
+ * loggers: [
20
+ * {
21
+ * category: "my-app",
22
+ * sinks: ["console"],
23
+ * level: "info",
24
+ * },
25
+ * {
26
+ * category: ["my-app", "sql"],
27
+ * filters: ["slow"],
28
+ * level: "debug",
29
+ * },
30
+ * {
31
+ * category: "logtape",
32
+ * sinks: ["console"],
33
+ * level: "error",
34
+ * },
35
+ * ],
36
+ * });
37
+ * ```
38
+ *
39
+ * @param config The configuration.
40
+ */
41
+ export function configure(config) {
42
+ if (configured && !config.reset) {
43
+ throw new ConfigError("Already configured; if you want to reset, turn on the reset flag.");
44
+ }
45
+ configured = true;
46
+ LoggerImpl.getLogger([]).resetDescendants();
47
+ let metaConfigured = false;
48
+ for (const cfg of config.loggers) {
49
+ if (cfg.category.length === 0 ||
50
+ (cfg.category.length === 1 && cfg.category[0] === "logtape") ||
51
+ (cfg.category.length === 2 &&
52
+ cfg.category[0] === "logtape" &&
53
+ cfg.category[1] === "meta")) {
54
+ metaConfigured = true;
55
+ }
56
+ const logger = LoggerImpl.getLogger(cfg.category);
57
+ for (const sinkId of cfg.sinks ?? []) {
58
+ const sink = config.sinks[sinkId];
59
+ if (!sink) {
60
+ reset();
61
+ throw new ConfigError(`Sink not found: ${sinkId}.`);
62
+ }
63
+ logger.sinks.push(sink);
64
+ }
65
+ if (cfg.level !== undefined)
66
+ logger.filters.push(toFilter(cfg.level));
67
+ for (const filterId of cfg.filters ?? []) {
68
+ const filter = config.filters[filterId];
69
+ if (filter === undefined) {
70
+ reset();
71
+ throw new ConfigError(`Filter not found: ${filterId}.`);
72
+ }
73
+ logger.filters.push(toFilter(filter));
74
+ }
75
+ }
76
+ const meta = LoggerImpl.getLogger(["logtape", "meta"]);
77
+ if (!metaConfigured) {
78
+ meta.sinks.push(getConsoleSink());
79
+ }
80
+ meta.info("LogTape loggers are configured. Note that LogTape itself uses the meta " +
81
+ "logger, which has category {metaLoggerCategory}. The meta logger " +
82
+ "purposes to log internal errors such as sink exceptions. If you " +
83
+ "are seeing this message, the meta logger is somehow configured. " +
84
+ "It's recommended to configure the meta logger with a separate sink " +
85
+ "so that you can easily notice if logging itself fails or is " +
86
+ "misconfigured. To turn off this message, configure the meta logger " +
87
+ "with higher log levels than {dismissLevel}.", { metaLoggerCategory: ["logtape", "meta"], dismissLevel: "info" });
88
+ }
89
+ /**
90
+ * Reset the configuration. Mostly for testing purposes.
91
+ */
92
+ export function reset() {
93
+ LoggerImpl.getLogger([]).resetDescendants();
94
+ configured = false;
95
+ }
96
+ /**
97
+ * A configuration error.
98
+ */
99
+ export class ConfigError extends Error {
100
+ /**
101
+ * Constructs a new configuration error.
102
+ * @param message The error message.
103
+ */
104
+ constructor(message) {
105
+ super(message);
106
+ this.name = "ConfigureError";
107
+ }
108
+ }
package/esm/filter.js ADDED
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Converts a {@link FilterLike} value to an actual {@link Filter}.
3
+ *
4
+ * @param filter The filter-like value to convert.
5
+ * @returns The actual filter.
6
+ */
7
+ export function toFilter(filter) {
8
+ if (typeof filter === "function")
9
+ return filter;
10
+ return getLevelFilter(filter);
11
+ }
12
+ /**
13
+ * Returns a filter that accepts log records with the specified level.
14
+ *
15
+ * @param level The level to filter by. If `null`, the filter will reject all
16
+ * records.
17
+ * @returns The filter.
18
+ */
19
+ export function getLevelFilter(level) {
20
+ if (level == null)
21
+ return () => false;
22
+ if (level === "fatal") {
23
+ return (record) => record.level === "fatal";
24
+ }
25
+ else if (level === "error") {
26
+ return (record) => record.level === "fatal" || record.level === "error";
27
+ }
28
+ else if (level === "warning") {
29
+ return (record) => record.level === "fatal" ||
30
+ record.level === "error" ||
31
+ record.level === "warning";
32
+ }
33
+ else if (level === "info") {
34
+ return (record) => record.level === "fatal" ||
35
+ record.level === "error" ||
36
+ record.level === "warning" ||
37
+ record.level === "info";
38
+ }
39
+ else if (level === "debug")
40
+ return () => true;
41
+ throw new TypeError(`Invalid log level: ${level}.`);
42
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * The severity level abbreviations.
3
+ */
4
+ const levelAbbreviations = {
5
+ "debug": "DBG",
6
+ "info": "INF",
7
+ "warning": "WRN",
8
+ "error": "ERR",
9
+ "fatal": "FTL",
10
+ };
11
+ /**
12
+ * A platform-specific inspect function. In Deno, this is {@link Deno.inspect},
13
+ * and in Node.js/Bun it is {@link util.inspect}. If neither is available, it
14
+ * falls back to {@link JSON.stringify}.
15
+ *
16
+ * @param value The value to inspect.
17
+ * @returns The string representation of the value.
18
+ */
19
+ const inspect = eval(`(
20
+ "Deno" in globalThis && "inspect" in globalThis.Deno &&
21
+ typeof globalThis.Deno.inspect === "function"
22
+ ? globalThis.Deno.inspect
23
+ : "util" in globalThis && "inspect" in globalThis.util &&
24
+ globalThis.util.inspect === "function"
25
+ ? globalThis.util.inspect
26
+ : JSON.stringify
27
+ )`);
28
+ /**
29
+ * The default text formatter. This formatter formats log records as follows:
30
+ *
31
+ * ```
32
+ * 2023-11-14 22:13:20.000 +00:00 [INF] Hello, world!
33
+ * ```
34
+ *
35
+ * @param record The log record to format.
36
+ * @returns The formatted log record.
37
+ */
38
+ export function defaultTextFormatter(record) {
39
+ const ts = new Date(record.timestamp);
40
+ let msg = "";
41
+ for (let i = 0; i < record.message.length; i++) {
42
+ if (i % 2 === 0)
43
+ msg += record.message[i];
44
+ else
45
+ msg += inspect(record.message[i]);
46
+ }
47
+ return `${ts.toISOString().replace("T", " ").replace("Z", " +00:00")} [${levelAbbreviations[record.level]}] ${msg}\n`;
48
+ }
49
+ /**
50
+ * The styles for the log level in the console.
51
+ */
52
+ const logLevelStyles = {
53
+ "debug": "background-color: gray; color: white;",
54
+ "info": "background-color: white; color: black;",
55
+ "warning": "background-color: orange;",
56
+ "error": "background-color: red;",
57
+ "fatal": "background-color: maroon;",
58
+ };
59
+ /**
60
+ * The default console formatter.
61
+ *
62
+ * @param record The log record to format.
63
+ * @returns The formatted log record, as an array of arguments for
64
+ * {@link console.log}.
65
+ */
66
+ export function defaultConsoleFormatter(record) {
67
+ let msg = "";
68
+ const values = [];
69
+ for (let i = 0; i < record.message.length; i++) {
70
+ if (i % 2 === 0)
71
+ msg += record.message[i];
72
+ else {
73
+ msg += "%o";
74
+ values.push(record.message[i]);
75
+ }
76
+ }
77
+ return [
78
+ `%c${record.level.toUpperCase()}%c %c${record.category.join("\xb7")} %c${msg}`,
79
+ logLevelStyles[record.level],
80
+ "background-color: default;",
81
+ "color: gray;",
82
+ "color: default;",
83
+ ...values,
84
+ ];
85
+ }
package/esm/logger.js ADDED
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Get a logger with the given category.
3
+ *
4
+ * ```typescript
5
+ * const logger = getLogger(["my-app"]);
6
+ * ```
7
+ *
8
+ * @param category The category of the logger. It can be a string or an array
9
+ * of strings. If it is a string, it is equivalent to an array
10
+ * with a single element.
11
+ * @returns The logger.
12
+ */
13
+ export function getLogger(category = []) {
14
+ return LoggerImpl.getLogger(category);
15
+ }
16
+ /**
17
+ * The root logger.
18
+ */
19
+ let rootLogger = null;
20
+ /**
21
+ * A logger implementation. Do not use this directly; use {@link getLogger}
22
+ * instead. This class is exported for testing purposes.
23
+ */
24
+ export class LoggerImpl {
25
+ static getLogger(category = []) {
26
+ if (rootLogger == null) {
27
+ rootLogger = new LoggerImpl(null, []);
28
+ }
29
+ if (typeof category === "string")
30
+ return rootLogger.getChild(category);
31
+ if (category.length === 0)
32
+ return rootLogger;
33
+ return rootLogger.getChild(category);
34
+ }
35
+ constructor(parent, category) {
36
+ Object.defineProperty(this, "parent", {
37
+ enumerable: true,
38
+ configurable: true,
39
+ writable: true,
40
+ value: void 0
41
+ });
42
+ Object.defineProperty(this, "children", {
43
+ enumerable: true,
44
+ configurable: true,
45
+ writable: true,
46
+ value: void 0
47
+ });
48
+ Object.defineProperty(this, "category", {
49
+ enumerable: true,
50
+ configurable: true,
51
+ writable: true,
52
+ value: void 0
53
+ });
54
+ Object.defineProperty(this, "sinks", {
55
+ enumerable: true,
56
+ configurable: true,
57
+ writable: true,
58
+ value: void 0
59
+ });
60
+ Object.defineProperty(this, "filters", {
61
+ enumerable: true,
62
+ configurable: true,
63
+ writable: true,
64
+ value: void 0
65
+ });
66
+ this.parent = parent;
67
+ this.children = {};
68
+ this.category = category;
69
+ this.sinks = [];
70
+ this.filters = [];
71
+ }
72
+ getChild(subcategory) {
73
+ const name = typeof subcategory === "string" ? subcategory : subcategory[0];
74
+ let child = this.children[name]?.deref();
75
+ if (child == null) {
76
+ child = new LoggerImpl(this, [...this.category, name]);
77
+ this.children[name] = new WeakRef(child);
78
+ }
79
+ if (typeof subcategory === "string" || subcategory.length === 1) {
80
+ return child;
81
+ }
82
+ return child.getChild(subcategory.slice(1));
83
+ }
84
+ /**
85
+ * Reset the logger. This removes all sinks and filters from the logger.
86
+ */
87
+ reset() {
88
+ while (this.sinks.length > 0)
89
+ this.sinks.shift();
90
+ while (this.filters.length > 0)
91
+ this.filters.shift();
92
+ }
93
+ /**
94
+ * Reset the logger and all its descendants. This removes all sinks and
95
+ * filters from the logger and all its descendants.
96
+ */
97
+ resetDescendants() {
98
+ for (const child of Object.values(this.children)) {
99
+ const logger = child.deref();
100
+ if (logger != null)
101
+ logger.resetDescendants();
102
+ }
103
+ this.reset();
104
+ }
105
+ filter(record) {
106
+ for (const filter of this.filters) {
107
+ if (!filter(record))
108
+ return false;
109
+ }
110
+ if (this.filters.length < 1)
111
+ return this.parent?.filter(record) ?? true;
112
+ return true;
113
+ }
114
+ *getSinks() {
115
+ if (this.parent != null) {
116
+ for (const sink of this.parent.getSinks())
117
+ yield sink;
118
+ }
119
+ for (const sink of this.sinks)
120
+ yield sink;
121
+ }
122
+ emit(record, bypassSinks) {
123
+ if (!this.filter(record))
124
+ return;
125
+ for (const sink of this.getSinks()) {
126
+ if (bypassSinks?.has(sink))
127
+ continue;
128
+ try {
129
+ sink(record);
130
+ }
131
+ catch (error) {
132
+ const bypassSinks2 = new Set(bypassSinks);
133
+ bypassSinks2.add(sink);
134
+ metaLogger.log("fatal", "Failed to emit a log record to sink {sink}: {error}", { sink, error, record }, bypassSinks2);
135
+ }
136
+ }
137
+ }
138
+ log(level, message, properties, bypassSinks) {
139
+ let cachedProps = undefined;
140
+ const record = typeof properties === "function"
141
+ ? {
142
+ category: this.category,
143
+ level,
144
+ timestamp: Date.now(),
145
+ get message() {
146
+ return parseMessageTemplate(message, this.properties);
147
+ },
148
+ get properties() {
149
+ if (cachedProps == null)
150
+ cachedProps = properties();
151
+ return cachedProps;
152
+ },
153
+ }
154
+ : {
155
+ category: this.category,
156
+ level,
157
+ timestamp: Date.now(),
158
+ message: parseMessageTemplate(message, properties),
159
+ properties,
160
+ };
161
+ this.emit(record, bypassSinks);
162
+ }
163
+ logLazily(level, callback) {
164
+ let msg = undefined;
165
+ this.emit({
166
+ category: this.category,
167
+ level,
168
+ get message() {
169
+ if (msg == null) {
170
+ msg = callback((tpl, ...values) => renderMessage(tpl, values));
171
+ }
172
+ return msg;
173
+ },
174
+ timestamp: Date.now(),
175
+ properties: {},
176
+ });
177
+ }
178
+ logTemplate(level, messageTemplate, values) {
179
+ this.emit({
180
+ category: this.category,
181
+ level,
182
+ message: renderMessage(messageTemplate, values),
183
+ timestamp: Date.now(),
184
+ properties: {},
185
+ });
186
+ }
187
+ debug(message, ...values) {
188
+ if (typeof message === "string") {
189
+ this.log("debug", message, (values[0] ?? {}));
190
+ }
191
+ else if (typeof message === "function") {
192
+ this.logLazily("debug", message);
193
+ }
194
+ else {
195
+ this.logTemplate("debug", message, values);
196
+ }
197
+ }
198
+ info(message, ...values) {
199
+ if (typeof message === "string") {
200
+ this.log("info", message, (values[0] ?? {}));
201
+ }
202
+ else if (typeof message === "function") {
203
+ this.logLazily("info", message);
204
+ }
205
+ else {
206
+ this.logTemplate("info", message, values);
207
+ }
208
+ }
209
+ warn(message, ...values) {
210
+ if (typeof message === "string") {
211
+ this.log("warning", message, (values[0] ?? {}));
212
+ }
213
+ else if (typeof message === "function") {
214
+ this.logLazily("warning", message);
215
+ }
216
+ else {
217
+ this.logTemplate("warning", message, values);
218
+ }
219
+ }
220
+ error(message, ...values) {
221
+ if (typeof message === "string") {
222
+ this.log("error", message, (values[0] ?? {}));
223
+ }
224
+ else if (typeof message === "function") {
225
+ this.logLazily("error", message);
226
+ }
227
+ else {
228
+ this.logTemplate("error", message, values);
229
+ }
230
+ }
231
+ fatal(message, ...values) {
232
+ if (typeof message === "string") {
233
+ this.log("fatal", message, (values[0] ?? {}));
234
+ }
235
+ else if (typeof message === "function") {
236
+ this.logLazily("fatal", message);
237
+ }
238
+ else {
239
+ this.logTemplate("fatal", message, values);
240
+ }
241
+ }
242
+ }
243
+ /**
244
+ * The meta logger. It is a logger with the category `["logtape", "meta"]`.
245
+ */
246
+ const metaLogger = LoggerImpl.getLogger(["logtape", "meta"]);
247
+ const MESSAGE_TEMPLATE_PATTERN = /\{([^}]*)\}/g;
248
+ /**
249
+ * Parse a message template into a message template array and a values array.
250
+ * @param template The message template.
251
+ * @param properties The values to replace placeholders with.
252
+ * @returns The message template array and the values array.
253
+ */
254
+ export function parseMessageTemplate(template, properties) {
255
+ let lastPos = 0;
256
+ const message = [];
257
+ while (true) {
258
+ const match = MESSAGE_TEMPLATE_PATTERN.exec(template);
259
+ if (match == null) {
260
+ message.push(template.substring(lastPos));
261
+ break;
262
+ }
263
+ message.push(template.substring(lastPos, match.index));
264
+ const key = match[1];
265
+ message.push(properties[key]);
266
+ lastPos = match.index + match[0].length;
267
+ }
268
+ return message;
269
+ }
270
+ /**
271
+ * Render a message template with values.
272
+ * @param template The message template.
273
+ * @param values The message template values.
274
+ * @returns The message template values interleaved between the substitution
275
+ * values.
276
+ */
277
+ export function renderMessage(template, values) {
278
+ const args = [];
279
+ for (let i = 0; i < template.length; i++) {
280
+ args.push(template[i]);
281
+ if (i < values.length)
282
+ args.push(values[i]);
283
+ }
284
+ return args;
285
+ }
package/esm/mod.js ADDED
@@ -0,0 +1,5 @@
1
+ export { ConfigError, configure, } from "./config.js";
2
+ export { getLevelFilter, toFilter, } from "./filter.js";
3
+ export { defaultConsoleFormatter, } from "./formatter.js";
4
+ export { getLogger } from "./logger.js";
5
+ export { getConsoleSink } from "./sink.js";
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
package/esm/record.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/esm/sink.js ADDED
@@ -0,0 +1,59 @@
1
+ import { defaultConsoleFormatter, defaultTextFormatter, } from "./formatter.js";
2
+ /**
3
+ * A factory that returns a sink that writes to a {@link WritableStream}.
4
+ *
5
+ * Note that the `stream` is of Web Streams API, which is different from
6
+ * Node.js streams. You can convert a Node.js stream to a Web Streams API
7
+ * stream using [`stream.Writable.toWeb()`] method.
8
+ *
9
+ * [`stream.Writable.toWeb()`]: https://nodejs.org/api/stream.html#streamwritabletowebstreamwritable
10
+ *
11
+ * @example Sink to the standard error in Deno
12
+ * ```typescript
13
+ * const stderrSink = getStreamSink(Deno.stderr.writable);
14
+ * ```
15
+ *
16
+ * @example Sink to the standard error in Node.js
17
+ * ```typescript
18
+ * import stream from "node:stream";
19
+ * const stderrSink = getStreamSink(stream.Writable.toWeb(process.stderr));
20
+ * ```
21
+ *
22
+ * @param stream The stream to write to.
23
+ * @param formatter The text formatter to use. Defaults to
24
+ * {@link defaultTextFormatter}.
25
+ * @param encoder The text encoder to use. Defaults to an instance of
26
+ * {@link TextEncoder}.
27
+ * @returns A sink that writes to the stream.
28
+ */
29
+ export function getStreamSink(stream, formatter = defaultTextFormatter, encoder = new TextEncoder()) {
30
+ const writer = stream.getWriter();
31
+ return (record) => {
32
+ const bytes = encoder.encode(formatter(record));
33
+ writer.ready.then(() => writer.write(bytes));
34
+ };
35
+ }
36
+ /**
37
+ * A console sink factory that returns a sink that logs to the console.
38
+ *
39
+ * @param formatter A console formatter. Defaults to
40
+ * {@link defaultConsoleFormatter}.
41
+ * @param console The console to log to. Defaults to {@link console}.
42
+ * @returns A sink that logs to the console.
43
+ */
44
+ export function getConsoleSink(formatter = defaultConsoleFormatter, console = globalThis.console) {
45
+ return (record) => {
46
+ const args = formatter(record);
47
+ if (record.level === "debug")
48
+ console.debug(...args);
49
+ else if (record.level === "info")
50
+ console.info(...args);
51
+ else if (record.level === "warning")
52
+ console.warn(...args);
53
+ else if (record.level === "error" || record.level === "fatal") {
54
+ console.error(...args);
55
+ }
56
+ else
57
+ throw new TypeError(`Invalid log level: ${record.level}.`);
58
+ };
59
+ }