@murky-web/simplelog 3.0.0 → 3.1.0

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.
package/README.md CHANGED
@@ -131,6 +131,31 @@ An explicit option always wins over the environment. Log files always get the
131
131
  ISO timestamp and never colors, whatever the console shows. The `web` entry has
132
132
  no terminal to ask: it keeps `"level"` and `"iso"`.
133
133
 
134
+ ### In the browser
135
+
136
+ Bundlers that build for the browser resolve `@murky-web/simplelog/web` through
137
+ its `browser` export condition to a smaller logger with the same API. It prints
138
+ differently:
139
+
140
+ - Arguments go to the console as they are, so DevTools shows objects you can
141
+ expand. Only the `Error` rules under "How arguments are printed" apply: an
142
+ `Error` argument is shown as a copy with `name`, `message`, `stack`, `cause`,
143
+ `code` and `errors`, and a `cause` that is no Error as `"[Object]"`. An Error
144
+ nested inside another object is shown in full.
145
+ - Only the header (timestamp, level, logger name, message) is colored, with CSS
146
+ through `%c`. `"syntax"` colors it like `"level"`; DevTools colors the values
147
+ itself. `"off"` leaves it plain.
148
+ - `writeToFile` and `logFilePath` do nothing.
149
+
150
+ Server runtimes keep the text logger: the `workerd`, `worker`, `edge-light`,
151
+ `deno`, `bun` and `node` conditions come before `browser`, and Vite's SSR build
152
+ resolves `node`. A bundler that builds server code with only the `browser`
153
+ condition gets the browser logger: `Error` arguments are still cut down, but
154
+ an Error inside another object, `Map` or `Set` keeps all its properties, and
155
+ nothing is truncated. Vite does that with `ssr.target: "webworker"` unless
156
+ `ssr.resolve.conditions` names one of the server conditions, for example
157
+ `["workerd", "worker"]`.
158
+
134
159
  `includeOpenTelemetryContext` is intentionally opt-in. When enabled, `simplelog`
135
160
  reads the current active span from `@opentelemetry/api` and appends `trace_id`
136
161
  and `span_id` to console and file output. It does not install an OpenTelemetry
@@ -203,7 +228,7 @@ the caller.
203
228
  - `@murky-web/simplelog/node`: explicit Node entry
204
229
  - `@murky-web/simplelog/bun`: Bun entry
205
230
  - `@murky-web/simplelog/web`: runtime-neutral console logger for fetch-style
206
- runtimes
231
+ runtimes, and a smaller one for browsers (see "In the browser")
207
232
  - `@murky-web/simplelog/hono`: Hono middleware for request-scoped logging
208
233
 
209
234
  For Bun, file appends intentionally use Bun's `node:fs` compatibility layer
@@ -0,0 +1,91 @@
1
+ import { formatConsoleTimestamp } from "./console_timestamp.js";
2
+ import { buildLogMessage, formatOpenTelemetryContextLabel } from "./logger_factory.js";
3
+ import { isError } from "./serialize_value.js";
4
+ // src/browser_console.ts
5
+ const EMPTY_LENGTH = 0;
6
+ const FIRST_DEPTH = 0;
7
+ const DEPTH_STEP = 1;
8
+ const FIRST_INDEX = 0;
9
+ const MAX_ERROR_DEPTH = 8;
10
+ const MAX_AGGREGATED_ERRORS = 50;
11
+ const MAX_DEPTH_LABEL = "[MaxDepth]";
12
+ const OBJECT_LABEL = "[Object]";
13
+ const LEVEL_STYLES = {
14
+ DEBUG: "color: #0891b2",
15
+ ERROR: "color: #dc2626",
16
+ INFO: "color: #16a34a",
17
+ WARN: "color: #ca8a04"
18
+ };
19
+ function readString(value, key, fallback) {
20
+ const property = Reflect.get(value, key);
21
+ if (typeof property === "string") return property;
22
+ return fallback;
23
+ }
24
+ /**
25
+ * Copies an Error with the text writer's allow-list only: `name`, `message`,
26
+ * `stack`, `cause`, `code` (a string or a number) and, for an `AggregateError`,
27
+ * `errors`. HTTP client errors (axios, got) carry the request, its headers and
28
+ * its body in other properties. The copy is a real Error, so DevTools still
29
+ * shows it with its stack.
30
+ *
31
+ * A `cause` or an element of `errors` is copied the same way when it is an
32
+ * Error; any other object becomes a label, as in the text writer's
33
+ * `serializeError`.
34
+ *
35
+ * @param {object} error - The Error.
36
+ * @param {number} depth - How deep in the Error chain it sits.
37
+ * @returns {unknown} The copy, or a label past the maximum depth.
38
+ */
39
+ function copyError(error, depth) {
40
+ if (depth > MAX_ERROR_DEPTH) return MAX_DEPTH_LABEL;
41
+ const copyChild = (value) => {
42
+ if (typeof value !== "object" || value === null) return value;
43
+ if (!isError(value)) return OBJECT_LABEL;
44
+ return copyError(value, depth + DEPTH_STEP);
45
+ };
46
+ const name = readString(error, "name", "Error");
47
+ const copy = new Error(readString(error, "message", ""));
48
+ const cause = Reflect.get(error, "cause");
49
+ const code = Reflect.get(error, "code");
50
+ const errors = Reflect.get(error, "errors");
51
+ copy.name = name;
52
+ copy.stack = readString(error, "stack", "");
53
+ if (typeof cause !== "undefined") copy.cause = copyChild(cause);
54
+ if (typeof code === "string" || typeof code === "number") Reflect.set(copy, "code", code);
55
+ if (name === "AggregateError" && Array.isArray(errors)) Reflect.set(copy, "errors", errors.slice(FIRST_INDEX, MAX_AGGREGATED_ERRORS).map((entry) => {
56
+ return copyChild(entry);
57
+ }));
58
+ return copy;
59
+ }
60
+ function toConsoleArgument(argument) {
61
+ if (typeof argument === "object" && argument !== null && isError(argument)) return copyError(argument, FIRST_DEPTH);
62
+ return argument;
63
+ }
64
+ /**
65
+ * The writer for browser DevTools. Arguments go to the console as they are, so
66
+ * objects stay expandable and DevTools colors values itself. Only the header is
67
+ * styled, with `%c` rather than ANSI codes, which Firefox does not render.
68
+ *
69
+ * The header is passed through `%s`, never as the format string itself: a `%`
70
+ * in a message or logger name would otherwise be read as a format specifier.
71
+ *
72
+ * An Error argument is copied with the text writer's allow-list (`copyError`),
73
+ * so a server bundle that resolves this writer by mistake does not print
74
+ * request headers either. Errors nested inside other objects are not walked:
75
+ * that needs the JSON serializer this writer leaves out.
76
+ *
77
+ * @param {LoggerConsole} loggerConsole - Where output goes.
78
+ * @returns {LogWriter} The runtime's `write`.
79
+ */
80
+ function createBrowserLogWriter(loggerConsole) {
81
+ return (entry, output) => {
82
+ const header = buildLogMessage(formatConsoleTimestamp(entry.epochMilliseconds, output.timestampFormat), `[${entry.level}]`, entry.loggerName, formatOpenTelemetryContextLabel(entry.openTelemetryContext), entry.message);
83
+ const args = entry.args.map(toConsoleArgument);
84
+ if (output.valueColorMode === "off") loggerConsole.log("%s", header, ...args);
85
+ else loggerConsole.log("%c%s", LEVEL_STYLES[entry.level], header, ...args);
86
+ if (entry.stackTrace.length > EMPTY_LENGTH) loggerConsole.error(entry.stackTrace);
87
+ };
88
+ }
89
+ export { createBrowserLogWriter };
90
+
91
+ //# sourceMappingURL=browser_console.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser_console.js","names":[],"sources":["../src/browser_console.ts"],"sourcesContent":["import { formatConsoleTimestamp } from \"./console_timestamp\";\nimport {\n buildLogMessage,\n formatOpenTelemetryContextLabel,\n} from \"./logger_factory\";\nimport type { LoggerConsole, LogLevel, LogWriter } from \"./logger_factory\";\nimport { isError } from \"./serialize_value\";\n\nconst EMPTY_LENGTH = 0;\nconst FIRST_DEPTH = 0;\nconst DEPTH_STEP = 1;\nconst FIRST_INDEX = 0;\nconst MAX_ERROR_DEPTH = 8;\nconst MAX_AGGREGATED_ERRORS = 50;\nconst MAX_DEPTH_LABEL = \"[MaxDepth]\";\nconst OBJECT_LABEL = \"[Object]\";\n\n// CSS colors for the header, close to the ANSI colors of the text writer and\n// readable on the light and the dark DevTools theme.\nconst LEVEL_STYLES: Readonly<Record<LogLevel, string>> = {\n DEBUG: \"color: #0891b2\",\n ERROR: \"color: #dc2626\",\n INFO: \"color: #16a34a\",\n WARN: \"color: #ca8a04\",\n};\n\nfunction readString(value: object, key: string, fallback: string): string {\n const property: unknown = Reflect.get(value, key);\n\n if (typeof property === \"string\") {\n return property;\n }\n\n return fallback;\n}\n\n/**\n * Copies an Error with the text writer's allow-list only: `name`, `message`,\n * `stack`, `cause`, `code` (a string or a number) and, for an `AggregateError`,\n * `errors`. HTTP client errors (axios, got) carry the request, its headers and\n * its body in other properties. The copy is a real Error, so DevTools still\n * shows it with its stack.\n *\n * A `cause` or an element of `errors` is copied the same way when it is an\n * Error; any other object becomes a label, as in the text writer's\n * `serializeError`.\n *\n * @param {object} error - The Error.\n * @param {number} depth - How deep in the Error chain it sits.\n * @returns {unknown} The copy, or a label past the maximum depth.\n */\nfunction copyError(error: object, depth: number): unknown {\n if (depth > MAX_ERROR_DEPTH) {\n return MAX_DEPTH_LABEL;\n }\n\n const copyChild = (value: unknown): unknown => {\n if (typeof value !== \"object\" || value === null) {\n return value;\n }\n\n if (!isError(value)) {\n return OBJECT_LABEL;\n }\n\n return copyError(value, depth + DEPTH_STEP);\n };\n const name = readString(error, \"name\", \"Error\");\n const copy = new Error(readString(error, \"message\", \"\"));\n const cause: unknown = Reflect.get(error, \"cause\");\n const code: unknown = Reflect.get(error, \"code\");\n const errors: unknown = Reflect.get(error, \"errors\");\n\n copy.name = name;\n copy.stack = readString(error, \"stack\", \"\");\n\n if (typeof cause !== \"undefined\") {\n copy.cause = copyChild(cause);\n }\n\n if (typeof code === \"string\" || typeof code === \"number\") {\n Reflect.set(copy, \"code\", code);\n }\n\n if (name === \"AggregateError\" && Array.isArray(errors)) {\n Reflect.set(\n copy,\n \"errors\",\n errors\n .slice(FIRST_INDEX, MAX_AGGREGATED_ERRORS)\n .map((entry: unknown) => {\n return copyChild(entry);\n }),\n );\n }\n\n return copy;\n}\n\nfunction toConsoleArgument(argument: unknown): unknown {\n if (\n typeof argument === \"object\" &&\n argument !== null &&\n isError(argument)\n ) {\n return copyError(argument, FIRST_DEPTH);\n }\n\n return argument;\n}\n\n/**\n * The writer for browser DevTools. Arguments go to the console as they are, so\n * objects stay expandable and DevTools colors values itself. Only the header is\n * styled, with `%c` rather than ANSI codes, which Firefox does not render.\n *\n * The header is passed through `%s`, never as the format string itself: a `%`\n * in a message or logger name would otherwise be read as a format specifier.\n *\n * An Error argument is copied with the text writer's allow-list (`copyError`),\n * so a server bundle that resolves this writer by mistake does not print\n * request headers either. Errors nested inside other objects are not walked:\n * that needs the JSON serializer this writer leaves out.\n *\n * @param {LoggerConsole} loggerConsole - Where output goes.\n * @returns {LogWriter} The runtime's `write`.\n */\nfunction createBrowserLogWriter(loggerConsole: LoggerConsole): LogWriter {\n return (entry, output) => {\n const header = buildLogMessage(\n formatConsoleTimestamp(\n entry.epochMilliseconds,\n output.timestampFormat,\n ),\n `[${entry.level}]`,\n entry.loggerName,\n formatOpenTelemetryContextLabel(entry.openTelemetryContext),\n entry.message,\n );\n const args = entry.args.map(toConsoleArgument);\n\n if (output.valueColorMode === \"off\") {\n loggerConsole.log(\"%s\", header, ...args);\n } else {\n loggerConsole.log(\n \"%c%s\",\n LEVEL_STYLES[entry.level],\n header,\n ...args,\n );\n }\n\n if (entry.stackTrace.length > EMPTY_LENGTH) {\n loggerConsole.error(entry.stackTrace);\n }\n };\n}\n\nexport { createBrowserLogWriter };\n"],"mappings":";;;;AAQA,MAAM,eAAe;AACrB,MAAM,cAAc;AACpB,MAAM,aAAa;AACnB,MAAM,cAAc;AACpB,MAAM,kBAAkB;AACxB,MAAM,wBAAwB;AAC9B,MAAM,kBAAkB;AACxB,MAAM,eAAe;AAIrB,MAAM,eAAmD;CACrD,OAAO;CACP,OAAO;CACP,MAAM;CACN,MAAM;AACV;AAEA,SAAS,WAAW,OAAe,KAAa,UAA0B;CACtE,MAAM,WAAoB,QAAQ,IAAI,OAAO,GAAG;CAEhD,IAAI,OAAO,aAAa,UACpB,OAAO;CAGX,OAAO;AACX;;;;;;;;;;;;;;;;AAiBA,SAAS,UAAU,OAAe,OAAwB;CACtD,IAAI,QAAQ,iBACR,OAAO;CAGX,MAAM,aAAa,UAA4B;EAC3C,IAAI,OAAO,UAAU,YAAY,UAAU,MACvC,OAAO;EAGX,IAAI,CAAC,QAAQ,KAAK,GACd,OAAO;EAGX,OAAO,UAAU,OAAO,QAAQ,UAAU;CAC9C;CACA,MAAM,OAAO,WAAW,OAAO,QAAQ,OAAO;CAC9C,MAAM,OAAO,IAAI,MAAM,WAAW,OAAO,WAAW,EAAE,CAAC;CACvD,MAAM,QAAiB,QAAQ,IAAI,OAAO,OAAO;CACjD,MAAM,OAAgB,QAAQ,IAAI,OAAO,MAAM;CAC/C,MAAM,SAAkB,QAAQ,IAAI,OAAO,QAAQ;CAEnD,KAAK,OAAO;CACZ,KAAK,QAAQ,WAAW,OAAO,SAAS,EAAE;CAE1C,IAAI,OAAO,UAAU,aACjB,KAAK,QAAQ,UAAU,KAAK;CAGhC,IAAI,OAAO,SAAS,YAAY,OAAO,SAAS,UAC5C,QAAQ,IAAI,MAAM,QAAQ,IAAI;CAGlC,IAAI,SAAS,oBAAoB,MAAM,QAAQ,MAAM,GACjD,QAAQ,IACJ,MACA,UACA,OACK,MAAM,aAAa,qBAAqB,CAAC,CACzC,KAAK,UAAmB;EACrB,OAAO,UAAU,KAAK;CAC1B,CAAC,CACT;CAGJ,OAAO;AACX;AAEA,SAAS,kBAAkB,UAA4B;CACnD,IACI,OAAO,aAAa,YACpB,aAAa,QACb,QAAQ,QAAQ,GAEhB,OAAO,UAAU,UAAU,WAAW;CAG1C,OAAO;AACX;;;;;;;;;;;;;;;;;AAkBA,SAAS,uBAAuB,eAAyC;CACrE,QAAQ,OAAO,WAAW;EACtB,MAAM,SAAS,gBACX,uBACI,MAAM,mBACN,OAAO,eACX,GACA,IAAI,MAAM,MAAM,IAChB,MAAM,YACN,gCAAgC,MAAM,oBAAoB,GAC1D,MAAM,OACV;EACA,MAAM,OAAO,MAAM,KAAK,IAAI,iBAAiB;EAE7C,IAAI,OAAO,mBAAmB,OAC1B,cAAc,IAAI,MAAM,QAAQ,GAAG,IAAI;OAEvC,cAAc,IACV,QACA,aAAa,MAAM,QACnB,QACA,GAAG,IACP;EAGJ,IAAI,MAAM,WAAW,SAAS,cAC1B,cAAc,MAAM,MAAM,UAAU;CAE5C;AACJ"}
@@ -0,0 +1,6 @@
1
+ import { LogLevel, LoggerBase, LoggerOptions, LoggerParent } from "./logger_factory.js";
2
+ declare class Logger extends LoggerBase {
3
+ constructor(name: string, parent?: LoggerParent, options?: LoggerOptions);
4
+ }
5
+ export { type LogLevel, Logger, type LoggerOptions };
6
+ //# sourceMappingURL=browser_logger.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser_logger.d.ts","names":[],"sources":["../src/browser_logger.ts"],"mappings":";cAkBM,eAAe;EACjB,YACI,cACA,SAAS,cACT,UAAS"}
@@ -0,0 +1,17 @@
1
+ import { createBrowserLogWriter } from "./browser_console.js";
2
+ import { LoggerBase, createLoggerConsole } from "./logger_factory.js";
3
+ // src/browser_logger.ts
4
+ /**
5
+ * What `@murky-web/simplelog/web` resolves to under the `browser` export
6
+ * condition. Same API as the `web` logger; see `createBrowserLogWriter` for how
7
+ * the output differs.
8
+ */
9
+ const browserRuntime = { write: createBrowserLogWriter(createLoggerConsole()) };
10
+ var Logger = class Logger extends LoggerBase {
11
+ constructor(name, parent, options = {}) {
12
+ super(Logger, browserRuntime, name, parent, options);
13
+ }
14
+ };
15
+ export { Logger };
16
+
17
+ //# sourceMappingURL=browser_logger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser_logger.js","names":[],"sources":["../src/browser_logger.ts"],"sourcesContent":["import { createBrowserLogWriter } from \"./browser_console\";\nimport { LoggerBase, createLoggerConsole } from \"./logger_factory\";\nimport type {\n LoggerOptions,\n LoggerParent,\n LoggerRuntime,\n LogLevel,\n} from \"./logger_factory\";\n\n/**\n * What `@murky-web/simplelog/web` resolves to under the `browser` export\n * condition. Same API as the `web` logger; see `createBrowserLogWriter` for how\n * the output differs.\n */\nconst browserRuntime = {\n write: createBrowserLogWriter(createLoggerConsole()),\n} satisfies LoggerRuntime;\n\nclass Logger extends LoggerBase {\n constructor(\n name: string,\n parent?: LoggerParent,\n options: LoggerOptions = {},\n ) {\n super(Logger, browserRuntime, name, parent, options);\n }\n}\n\nexport { Logger };\n\nexport type { LoggerOptions, LogLevel };\n"],"mappings":";;;;;;;;AAcA,MAAM,iBAAiB,EACnB,OAAO,uBAAuB,oBAAoB,CAAC,EACvD;AAEA,IAAM,SAAN,MAAM,eAAe,WAAW;CAC5B,YACI,MACA,QACA,UAAyB,CAAC,GAC5B;EACE,MAAM,QAAQ,gBAAgB,MAAM,QAAQ,OAAO;CACvD;AACJ"}
@@ -0,0 +1,25 @@
1
+ import { LogFileWriter } from "./log_file.js";
2
+ import { LogWriter, LoggerConsole } from "./logger_factory.js";
3
+ type StringifiedArgument = Readonly<{
4
+ /**
5
+ * The JSON-safe value behind an object's `text`. The log file writes it as
6
+ * compact JSON; it is only serialized again when a file is written.
7
+ */
8
+ jsonValue?: unknown;
9
+ kind: StringifiedArgumentKind;
10
+ text: string;
11
+ }>;
12
+ type StringifiedArgumentKind = "boolean" | "function" | "nullish" | "number" | "object" | "string" | "symbol";
13
+ /**
14
+ * The writer for terminals and server logs: every argument is turned into text
15
+ * (objects as JSON, with the safety rules of `toJsonSafeValue`), colored with
16
+ * ANSI codes unless `valueColorMode` is `"off"`.
17
+ *
18
+ * @param {LoggerConsole} loggerConsole - Where console output goes.
19
+ * @param {LogFileWriter} [writeLogFile] - Writes the log file; only runtimes
20
+ * that can write files pass one.
21
+ * @returns {LogWriter} The runtime's `write`.
22
+ */
23
+ declare function createTextLogWriter(loggerConsole: LoggerConsole, writeLogFile?: LogFileWriter): LogWriter;
24
+ export { type StringifiedArgument, createTextLogWriter };
25
+ //# sourceMappingURL=console_text.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"console_text.d.ts","names":[],"sources":["../src/console_text.ts"],"mappings":";;KAqCK,sBAAsB;;;;;EAKvB;EACA,MAAM;EACN;;KAGC;;;;;;;;;;;iBAmUI,oBACL,eAAe,eACf,eAAe,gBAChB"}
@@ -0,0 +1,168 @@
1
+ import { formatConsoleTimestamp } from "./console_timestamp.js";
2
+ import { buildLogMessage, formatOpenTelemetryContextLabel } from "./logger_factory.js";
3
+ import { formatFunctionLabel, toJsonSafeValue } from "./serialize_value.js";
4
+ // src/console_text.ts
5
+ const ANSI_RESET_COLOR = 0;
6
+ const ANSI_GREEN = 32;
7
+ const ANSI_YELLOW = 33;
8
+ const ANSI_RED = 31;
9
+ const ANSI_CYAN = 36;
10
+ const ANSI_BLUE = 34;
11
+ const ANSI_MAGENTA = 35;
12
+ const ANSI_GRAY = 90;
13
+ const EMPTY_LENGTH = 0;
14
+ const JSON_INDENTATION = 2;
15
+ const FALLBACK_OBJECT_STRING = "[Object]";
16
+ const LOG_LEVEL_COLORS = {
17
+ DEBUG: ANSI_CYAN,
18
+ ERROR: ANSI_RED,
19
+ INFO: ANSI_GREEN,
20
+ WARN: ANSI_YELLOW
21
+ };
22
+ function colorize(text, colorCode) {
23
+ return `\u001B[${colorCode}m${text}\u001B[${ANSI_RESET_COLOR}m`;
24
+ }
25
+ function isPrimitiveArgument(argument) {
26
+ return typeof argument === "bigint" || typeof argument === "boolean" || typeof argument === "number" || typeof argument === "string" || typeof argument === "symbol";
27
+ }
28
+ function stringifyPrimitiveArgument(argument) {
29
+ if (typeof argument === "string") return {
30
+ kind: "string",
31
+ text: argument
32
+ };
33
+ if (typeof argument === "symbol") return {
34
+ kind: "symbol",
35
+ text: argument.toString()
36
+ };
37
+ if (typeof argument === "boolean") return {
38
+ kind: "boolean",
39
+ text: `${argument}`
40
+ };
41
+ return {
42
+ kind: "number",
43
+ text: `${argument}`
44
+ };
45
+ }
46
+ function stringifyFunctionArgument(functionName) {
47
+ return {
48
+ kind: "function",
49
+ text: formatFunctionLabel(functionName)
50
+ };
51
+ }
52
+ function stringifyJsonArgument(argument) {
53
+ try {
54
+ const safeValue = toJsonSafeValue(argument);
55
+ const stringifiedArgument = JSON.stringify(safeValue, void 0, JSON_INDENTATION);
56
+ if (typeof stringifiedArgument !== "string") return {
57
+ kind: "object",
58
+ text: FALLBACK_OBJECT_STRING
59
+ };
60
+ return {
61
+ jsonValue: safeValue,
62
+ kind: "object",
63
+ text: stringifiedArgument
64
+ };
65
+ } catch {
66
+ return {
67
+ kind: "object",
68
+ text: FALLBACK_OBJECT_STRING
69
+ };
70
+ }
71
+ }
72
+ function stringifyArgument(argument) {
73
+ if (typeof argument === "undefined") return {
74
+ kind: "nullish",
75
+ text: "undefined"
76
+ };
77
+ if (argument === null) return {
78
+ kind: "nullish",
79
+ text: "null"
80
+ };
81
+ if (isPrimitiveArgument(argument)) return stringifyPrimitiveArgument(argument);
82
+ if (typeof argument === "function") return stringifyFunctionArgument(argument.name);
83
+ return stringifyJsonArgument(argument);
84
+ }
85
+ function stringifyArguments(argumentsList) {
86
+ return argumentsList.map((argument) => {
87
+ return stringifyArgument(argument);
88
+ });
89
+ }
90
+ function buildColoredLogMessage(level, timestamp, loggerName, openTelemetryContextLabel, message) {
91
+ const colorCode = LOG_LEVEL_COLORS[level];
92
+ return buildLogMessage(colorize(timestamp, colorCode), colorize(`[${level}]`, colorCode), colorize(loggerName, colorCode), openTelemetryContextLabel, colorize(message, colorCode));
93
+ }
94
+ function colorizeOpenTelemetryContextLabel(level, openTelemetryContext, valueColorMode) {
95
+ const plainOpenTelemetryContextLabel = formatOpenTelemetryContextLabel(openTelemetryContext);
96
+ if (valueColorMode === "off" || plainOpenTelemetryContextLabel.length === EMPTY_LENGTH) return plainOpenTelemetryContextLabel;
97
+ if (valueColorMode === "syntax") return colorize(plainOpenTelemetryContextLabel, ANSI_GRAY);
98
+ return colorize(plainOpenTelemetryContextLabel, LOG_LEVEL_COLORS[level]);
99
+ }
100
+ function getSyntaxColorCode(kind) {
101
+ switch (kind) {
102
+ case "boolean": return ANSI_YELLOW;
103
+ case "function": return ANSI_MAGENTA;
104
+ case "nullish": return ANSI_GRAY;
105
+ case "number": return ANSI_CYAN;
106
+ case "object": return ANSI_BLUE;
107
+ case "string": return ANSI_GREEN;
108
+ case "symbol": return ANSI_MAGENTA;
109
+ default: return ANSI_GREEN;
110
+ }
111
+ }
112
+ function colorizeArguments(argumentsList, level, valueColorMode) {
113
+ if (valueColorMode === "off") return argumentsList.map((argument) => {
114
+ return argument.text;
115
+ });
116
+ if (valueColorMode === "syntax") return argumentsList.map((argument) => {
117
+ return colorize(argument.text, getSyntaxColorCode(argument.kind));
118
+ });
119
+ const colorCode = LOG_LEVEL_COLORS[level];
120
+ return argumentsList.map((argument) => {
121
+ return colorize(argument.text, colorCode);
122
+ });
123
+ }
124
+ function buildPlainConsoleLogMessage(level, timestamp, loggerName, openTelemetryContext, message) {
125
+ return buildLogMessage(timestamp, `[${level}]`, loggerName, formatOpenTelemetryContextLabel(openTelemetryContext), message);
126
+ }
127
+ function buildConsoleLogMessage(level, timestamp, loggerName, openTelemetryContext, message, valueColorMode) {
128
+ if (valueColorMode === "off") return buildPlainConsoleLogMessage(level, timestamp, loggerName, openTelemetryContext, message);
129
+ return buildColoredLogMessage(level, timestamp, loggerName, colorizeOpenTelemetryContextLabel(level, openTelemetryContext, valueColorMode), message);
130
+ }
131
+ function buildConsoleStackTrace(stackTrace, level, valueColorMode) {
132
+ if (valueColorMode === "off") return stackTrace;
133
+ return colorize(stackTrace, LOG_LEVEL_COLORS[level]);
134
+ }
135
+ function createConsolePayload(entry, args, output) {
136
+ const { level } = entry;
137
+ const { valueColorMode } = output;
138
+ return {
139
+ consoleArgs: colorizeArguments(args, level, valueColorMode),
140
+ consoleLogMessage: buildConsoleLogMessage(level, formatConsoleTimestamp(entry.epochMilliseconds, output.timestampFormat), entry.loggerName, entry.openTelemetryContext, entry.message, valueColorMode),
141
+ consoleStackTrace: buildConsoleStackTrace(entry.stackTrace, level, valueColorMode)
142
+ };
143
+ }
144
+ /**
145
+ * The writer for terminals and server logs: every argument is turned into text
146
+ * (objects as JSON, with the safety rules of `toJsonSafeValue`), colored with
147
+ * ANSI codes unless `valueColorMode` is `"off"`.
148
+ *
149
+ * @param {LoggerConsole} loggerConsole - Where console output goes.
150
+ * @param {LogFileWriter} [writeLogFile] - Writes the log file; only runtimes
151
+ * that can write files pass one.
152
+ * @returns {LogWriter} The runtime's `write`.
153
+ */
154
+ function createTextLogWriter(loggerConsole, writeLogFile) {
155
+ return (entry, output) => {
156
+ const args = stringifyArguments(entry.args);
157
+ if (output.writeToFile && typeof writeLogFile === "function") writeLogFile(output.logFilePath, {
158
+ ...entry,
159
+ args
160
+ });
161
+ const payload = createConsolePayload(entry, args, output);
162
+ loggerConsole.log(payload.consoleLogMessage, ...payload.consoleArgs);
163
+ if (entry.stackTrace.length > EMPTY_LENGTH) loggerConsole.error(payload.consoleStackTrace);
164
+ };
165
+ }
166
+ export { createTextLogWriter };
167
+
168
+ //# sourceMappingURL=console_text.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"console_text.js","names":[],"sources":["../src/console_text.ts"],"sourcesContent":["import { formatConsoleTimestamp } from \"./console_timestamp\";\nimport type { LogFileWriter } from \"./log_file\";\nimport {\n buildLogMessage,\n formatOpenTelemetryContextLabel,\n} from \"./logger_factory\";\nimport type {\n LogEntry,\n LoggerConsole,\n LogLevel,\n LogOutput,\n LogWriter,\n OpenTelemetryContext,\n ValueColorMode,\n} from \"./logger_factory\";\nimport { formatFunctionLabel, toJsonSafeValue } from \"./serialize_value\";\n\nconst ANSI_RESET_COLOR = 0;\nconst ANSI_GREEN = 32;\nconst ANSI_YELLOW = 33;\nconst ANSI_RED = 31;\nconst ANSI_CYAN = 36;\nconst ANSI_BLUE = 34;\nconst ANSI_MAGENTA = 35;\nconst ANSI_GRAY = 90;\nconst EMPTY_LENGTH = 0;\nconst JSON_INDENTATION = 2;\nconst FALLBACK_OBJECT_STRING = \"[Object]\";\n\ntype ConsolePayload = Readonly<{\n consoleArgs: readonly string[];\n consoleLogMessage: string;\n consoleStackTrace: string;\n}>;\n\ntype StringifiablePrimitive = bigint | boolean | number | string | symbol;\n\ntype StringifiedArgument = Readonly<{\n /**\n * The JSON-safe value behind an object's `text`. The log file writes it as\n * compact JSON; it is only serialized again when a file is written.\n */\n jsonValue?: unknown;\n kind: StringifiedArgumentKind;\n text: string;\n}>;\n\ntype StringifiedArgumentKind =\n | \"boolean\"\n | \"function\"\n | \"nullish\"\n | \"number\"\n | \"object\"\n | \"string\"\n | \"symbol\";\n\nconst LOG_LEVEL_COLORS: Readonly<Record<LogLevel, number>> = {\n DEBUG: ANSI_CYAN,\n ERROR: ANSI_RED,\n INFO: ANSI_GREEN,\n WARN: ANSI_YELLOW,\n};\n\nfunction colorize(text: string, colorCode: number): string {\n return `\\u001B[${colorCode}m${text}\\u001B[${ANSI_RESET_COLOR}m`;\n}\n\nfunction isPrimitiveArgument(\n argument: unknown,\n): argument is StringifiablePrimitive {\n return (\n typeof argument === \"bigint\" ||\n typeof argument === \"boolean\" ||\n typeof argument === \"number\" ||\n typeof argument === \"string\" ||\n typeof argument === \"symbol\"\n );\n}\n\nfunction stringifyPrimitiveArgument(\n argument: StringifiablePrimitive,\n): StringifiedArgument {\n if (typeof argument === \"string\") {\n return {\n kind: \"string\",\n text: argument,\n };\n }\n\n if (typeof argument === \"symbol\") {\n return {\n kind: \"symbol\",\n text: argument.toString(),\n };\n }\n\n if (typeof argument === \"boolean\") {\n return {\n kind: \"boolean\",\n text: `${argument}`,\n };\n }\n\n return {\n kind: \"number\",\n text: `${argument}`,\n };\n}\n\nfunction stringifyFunctionArgument(functionName: string): StringifiedArgument {\n return {\n kind: \"function\",\n text: formatFunctionLabel(functionName),\n };\n}\n\nfunction stringifyJsonArgument(argument: unknown): StringifiedArgument {\n try {\n const safeValue = toJsonSafeValue(argument);\n const stringifiedArgument = JSON.stringify(\n safeValue,\n undefined,\n JSON_INDENTATION,\n );\n\n if (typeof stringifiedArgument !== \"string\") {\n return {\n kind: \"object\",\n text: FALLBACK_OBJECT_STRING,\n };\n }\n\n return {\n jsonValue: safeValue,\n kind: \"object\",\n text: stringifiedArgument,\n };\n } catch {\n return {\n kind: \"object\",\n text: FALLBACK_OBJECT_STRING,\n };\n }\n}\n\nfunction stringifyArgument(argument: unknown): StringifiedArgument {\n if (typeof argument === \"undefined\") {\n return {\n kind: \"nullish\",\n text: \"undefined\",\n };\n }\n\n if (argument === null) {\n return {\n kind: \"nullish\",\n text: \"null\",\n };\n }\n\n if (isPrimitiveArgument(argument)) {\n return stringifyPrimitiveArgument(argument);\n }\n\n if (typeof argument === \"function\") {\n return stringifyFunctionArgument(argument.name);\n }\n\n return stringifyJsonArgument(argument);\n}\n\nfunction stringifyArguments(\n argumentsList: readonly unknown[],\n): readonly StringifiedArgument[] {\n return argumentsList.map((argument) => {\n return stringifyArgument(argument);\n });\n}\n\nfunction buildColoredLogMessage(\n level: LogLevel,\n timestamp: string,\n loggerName: string,\n openTelemetryContextLabel: string,\n message: string,\n): string {\n const colorCode = LOG_LEVEL_COLORS[level];\n\n return buildLogMessage(\n colorize(timestamp, colorCode),\n colorize(`[${level}]`, colorCode),\n colorize(loggerName, colorCode),\n openTelemetryContextLabel,\n colorize(message, colorCode),\n );\n}\n\nfunction colorizeOpenTelemetryContextLabel(\n level: LogLevel,\n openTelemetryContext: OpenTelemetryContext | undefined,\n valueColorMode: ValueColorMode,\n): string {\n const plainOpenTelemetryContextLabel =\n formatOpenTelemetryContextLabel(openTelemetryContext);\n\n if (\n valueColorMode === \"off\" ||\n plainOpenTelemetryContextLabel.length === EMPTY_LENGTH\n ) {\n return plainOpenTelemetryContextLabel;\n }\n\n if (valueColorMode === \"syntax\") {\n return colorize(plainOpenTelemetryContextLabel, ANSI_GRAY);\n }\n\n return colorize(plainOpenTelemetryContextLabel, LOG_LEVEL_COLORS[level]);\n}\n\nfunction getSyntaxColorCode(kind: StringifiedArgumentKind): number {\n switch (kind) {\n case \"boolean\": {\n return ANSI_YELLOW;\n }\n case \"function\": {\n return ANSI_MAGENTA;\n }\n case \"nullish\": {\n return ANSI_GRAY;\n }\n case \"number\": {\n return ANSI_CYAN;\n }\n case \"object\": {\n return ANSI_BLUE;\n }\n case \"string\": {\n return ANSI_GREEN;\n }\n case \"symbol\": {\n return ANSI_MAGENTA;\n }\n default: {\n return ANSI_GREEN;\n }\n }\n}\n\nfunction colorizeArguments(\n argumentsList: readonly StringifiedArgument[],\n level: LogLevel,\n valueColorMode: ValueColorMode,\n): readonly string[] {\n if (valueColorMode === \"off\") {\n return argumentsList.map((argument) => {\n return argument.text;\n });\n }\n\n if (valueColorMode === \"syntax\") {\n return argumentsList.map((argument) => {\n return colorize(argument.text, getSyntaxColorCode(argument.kind));\n });\n }\n\n const colorCode = LOG_LEVEL_COLORS[level];\n\n return argumentsList.map((argument) => {\n return colorize(argument.text, colorCode);\n });\n}\n\nfunction buildPlainConsoleLogMessage(\n level: LogLevel,\n timestamp: string,\n loggerName: string,\n openTelemetryContext: OpenTelemetryContext | undefined,\n message: string,\n): string {\n return buildLogMessage(\n timestamp,\n `[${level}]`,\n loggerName,\n formatOpenTelemetryContextLabel(openTelemetryContext),\n message,\n );\n}\n\nfunction buildConsoleLogMessage(\n level: LogLevel,\n timestamp: string,\n loggerName: string,\n openTelemetryContext: OpenTelemetryContext | undefined,\n message: string,\n valueColorMode: ValueColorMode,\n): string {\n if (valueColorMode === \"off\") {\n return buildPlainConsoleLogMessage(\n level,\n timestamp,\n loggerName,\n openTelemetryContext,\n message,\n );\n }\n\n return buildColoredLogMessage(\n level,\n timestamp,\n loggerName,\n colorizeOpenTelemetryContextLabel(\n level,\n openTelemetryContext,\n valueColorMode,\n ),\n message,\n );\n}\n\nfunction buildConsoleStackTrace(\n stackTrace: string,\n level: LogLevel,\n valueColorMode: ValueColorMode,\n): string {\n if (valueColorMode === \"off\") {\n return stackTrace;\n }\n\n return colorize(stackTrace, LOG_LEVEL_COLORS[level]);\n}\n\nfunction createConsolePayload(\n entry: LogEntry,\n args: readonly StringifiedArgument[],\n output: LogOutput,\n): ConsolePayload {\n const { level } = entry;\n const { valueColorMode } = output;\n\n return {\n consoleArgs: colorizeArguments(args, level, valueColorMode),\n consoleLogMessage: buildConsoleLogMessage(\n level,\n formatConsoleTimestamp(\n entry.epochMilliseconds,\n output.timestampFormat,\n ),\n entry.loggerName,\n entry.openTelemetryContext,\n entry.message,\n valueColorMode,\n ),\n consoleStackTrace: buildConsoleStackTrace(\n entry.stackTrace,\n level,\n valueColorMode,\n ),\n };\n}\n\n/**\n * The writer for terminals and server logs: every argument is turned into text\n * (objects as JSON, with the safety rules of `toJsonSafeValue`), colored with\n * ANSI codes unless `valueColorMode` is `\"off\"`.\n *\n * @param {LoggerConsole} loggerConsole - Where console output goes.\n * @param {LogFileWriter} [writeLogFile] - Writes the log file; only runtimes\n * that can write files pass one.\n * @returns {LogWriter} The runtime's `write`.\n */\nfunction createTextLogWriter(\n loggerConsole: LoggerConsole,\n writeLogFile?: LogFileWriter,\n): LogWriter {\n return (entry, output) => {\n const args = stringifyArguments(entry.args);\n\n if (output.writeToFile && typeof writeLogFile === \"function\") {\n writeLogFile(output.logFilePath, { ...entry, args });\n }\n\n const payload = createConsolePayload(entry, args, output);\n\n loggerConsole.log(payload.consoleLogMessage, ...payload.consoleArgs);\n if (entry.stackTrace.length > EMPTY_LENGTH) {\n loggerConsole.error(payload.consoleStackTrace);\n }\n };\n}\n\nexport { createTextLogWriter };\nexport type { StringifiedArgument };\n"],"mappings":"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"}
@@ -0,0 +1,9 @@
1
+ import { StringifiedArgument } from "./console_text.js";
2
+ import { LogEntry } from "./logger_factory.js";
3
+ /** A log entry with its arguments already turned into text. */
4
+ type LogFileEntry = Readonly<Omit<LogEntry, "args"> & {
5
+ args: readonly StringifiedArgument[];
6
+ }>;
7
+ type LogFileWriter = (filePath: string, entry: LogFileEntry) => void;
8
+ export type { LogFileEntry, LogFileWriter };
9
+ //# sourceMappingURL=log_file.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log_file.d.ts","names":[],"sources":["../src/log_file.ts"],"mappings":";;;KAcK,eAAe,SAChB,KAAK;EACD,eAAe;;KAIlB,iBAAiB,kBAAkB,OAAO"}
@@ -0,0 +1,52 @@
1
+ import { buildLogMessage, formatOpenTelemetryContextLabel } from "./logger_factory.js";
2
+ import { escapeFileCharacters } from "./serialize_value.js";
3
+ // src/log_file.ts
4
+ const LINE_BREAK = "\n";
5
+ const ARGUMENT_SEPARATOR = " ";
6
+ const STACK_CONTINUATION_PREFIX = " ";
7
+ const EMPTY_LENGTH = 0;
8
+ function formatFileArgument(argument) {
9
+ if (argument.kind === "object" && "jsonValue" in argument) return escapeFileCharacters(JSON.stringify(argument.jsonValue));
10
+ return escapeFileCharacters(argument.text);
11
+ }
12
+ /**
13
+ * The file line is the console line without colors and with the ISO timestamp:
14
+ * the header, then every argument, separated by a space the way `console.log`
15
+ * separates them.
16
+ *
17
+ * @param {LogFileEntry} entry - The log call.
18
+ * @returns {string} One log file line, without the trailing line break.
19
+ */
20
+ function buildFileLine(entry) {
21
+ return [escapeFileCharacters(buildLogMessage(new Date(entry.epochMilliseconds).toISOString(), `[${entry.level}]`, entry.loggerName, formatOpenTelemetryContextLabel(entry.openTelemetryContext), entry.message)), ...entry.args.map(formatFileArgument)].join(ARGUMENT_SEPARATOR);
22
+ }
23
+ /**
24
+ * A stack trace is several lines. Every one of them starts with a tab in the
25
+ * file, while every log entry starts with a timestamp, so a reader can tell the
26
+ * continuation lines of an entry from the next entry.
27
+ *
28
+ * @param {string} stackTrace - The plain stack trace.
29
+ * @returns {string} The stack trace, each line tab-prefixed and escaped.
30
+ */
31
+ function formatFileStackTrace(stackTrace) {
32
+ return stackTrace.split(LINE_BREAK).map((line) => {
33
+ return `${STACK_CONTINUATION_PREFIX}${escapeFileCharacters(line)}`;
34
+ }).join(LINE_BREAK);
35
+ }
36
+ /**
37
+ * The log file writer for runtimes that can append to a file. Only those import
38
+ * this module, so the `web` entry never bundles it.
39
+ *
40
+ * @param {(filePath: string, content: string) => void} appendTextFileSync -
41
+ * Appends text to the file, creating it when it is missing.
42
+ * @returns {LogFileWriter} Writes one entry, then its stack trace, if any.
43
+ */
44
+ function createLogFileWriter(appendTextFileSync) {
45
+ return (filePath, entry) => {
46
+ appendTextFileSync(filePath, `${buildFileLine(entry)}${LINE_BREAK}`);
47
+ if (entry.stackTrace.length > EMPTY_LENGTH) appendTextFileSync(filePath, `${formatFileStackTrace(entry.stackTrace)}${LINE_BREAK}`);
48
+ };
49
+ }
50
+ export { createLogFileWriter };
51
+
52
+ //# sourceMappingURL=log_file.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log_file.js","names":[],"sources":["../src/log_file.ts"],"sourcesContent":["import type { StringifiedArgument } from \"./console_text\";\nimport {\n buildLogMessage,\n formatOpenTelemetryContextLabel,\n} from \"./logger_factory\";\nimport type { LogEntry } from \"./logger_factory\";\nimport { escapeFileCharacters } from \"./serialize_value\";\n\nconst LINE_BREAK = \"\\n\";\nconst ARGUMENT_SEPARATOR = \" \";\nconst STACK_CONTINUATION_PREFIX = \"\\t\";\nconst EMPTY_LENGTH = 0;\n\n/** A log entry with its arguments already turned into text. */\ntype LogFileEntry = Readonly<\n Omit<LogEntry, \"args\"> & {\n args: readonly StringifiedArgument[];\n }\n>;\n\ntype LogFileWriter = (filePath: string, entry: LogFileEntry) => void;\n\nfunction formatFileArgument(argument: StringifiedArgument): string {\n // Objects use their compact, single-line JSON. JSON already escaped the\n // control characters below U+0020; the rest (DEL, C1, U+2028, bidi\n // controls) is escaped here, and an escape inside a JSON string is still\n // valid JSON.\n if (argument.kind === \"object\" && \"jsonValue\" in argument) {\n return escapeFileCharacters(JSON.stringify(argument.jsonValue));\n }\n\n return escapeFileCharacters(argument.text);\n}\n\n/**\n * The file line is the console line without colors and with the ISO timestamp:\n * the header, then every argument, separated by a space the way `console.log`\n * separates them.\n *\n * @param {LogFileEntry} entry - The log call.\n * @returns {string} One log file line, without the trailing line break.\n */\nfunction buildFileLine(entry: LogFileEntry): string {\n const header = escapeFileCharacters(\n buildLogMessage(\n new Date(entry.epochMilliseconds).toISOString(),\n `[${entry.level}]`,\n entry.loggerName,\n formatOpenTelemetryContextLabel(entry.openTelemetryContext),\n entry.message,\n ),\n );\n\n return [header, ...entry.args.map(formatFileArgument)].join(\n ARGUMENT_SEPARATOR,\n );\n}\n\n/**\n * A stack trace is several lines. Every one of them starts with a tab in the\n * file, while every log entry starts with a timestamp, so a reader can tell the\n * continuation lines of an entry from the next entry.\n *\n * @param {string} stackTrace - The plain stack trace.\n * @returns {string} The stack trace, each line tab-prefixed and escaped.\n */\nfunction formatFileStackTrace(stackTrace: string): string {\n return stackTrace\n .split(LINE_BREAK)\n .map((line) => {\n return `${STACK_CONTINUATION_PREFIX}${escapeFileCharacters(line)}`;\n })\n .join(LINE_BREAK);\n}\n\n/**\n * The log file writer for runtimes that can append to a file. Only those import\n * this module, so the `web` entry never bundles it.\n *\n * @param {(filePath: string, content: string) => void} appendTextFileSync -\n * Appends text to the file, creating it when it is missing.\n * @returns {LogFileWriter} Writes one entry, then its stack trace, if any.\n */\nfunction createLogFileWriter(\n appendTextFileSync: (filePath: string, content: string) => void,\n): LogFileWriter {\n return (filePath, entry) => {\n appendTextFileSync(filePath, `${buildFileLine(entry)}${LINE_BREAK}`);\n\n if (entry.stackTrace.length > EMPTY_LENGTH) {\n appendTextFileSync(\n filePath,\n `${formatFileStackTrace(entry.stackTrace)}${LINE_BREAK}`,\n );\n }\n };\n}\n\nexport { createLogFileWriter };\nexport type { LogFileEntry, LogFileWriter };\n"],"mappings":";;;AAQA,MAAM,aAAa;AACnB,MAAM,qBAAqB;AAC3B,MAAM,4BAA4B;AAClC,MAAM,eAAe;AAWrB,SAAS,mBAAmB,UAAuC;CAK/D,IAAI,SAAS,SAAS,YAAY,eAAe,UAC7C,OAAO,qBAAqB,KAAK,UAAU,SAAS,SAAS,CAAC;CAGlE,OAAO,qBAAqB,SAAS,IAAI;AAC7C;;;;;;;;;AAUA,SAAS,cAAc,OAA6B;CAWhD,OAAO,CAVQ,qBACX,gBACI,IAAI,KAAK,MAAM,iBAAiB,CAAC,CAAC,YAAY,GAC9C,IAAI,MAAM,MAAM,IAChB,MAAM,YACN,gCAAgC,MAAM,oBAAoB,GAC1D,MAAM,OACV,CAGS,GAAG,GAAG,MAAM,KAAK,IAAI,kBAAkB,CAAC,CAAC,CAAC,KACnD,kBACJ;AACJ;;;;;;;;;AAUA,SAAS,qBAAqB,YAA4B;CACtD,OAAO,WACF,MAAM,UAAU,CAAC,CACjB,KAAK,SAAS;EACX,OAAO,GAAG,4BAA4B,qBAAqB,IAAI;CACnE,CAAC,CAAC,CACD,KAAK,UAAU;AACxB;;;;;;;;;AAUA,SAAS,oBACL,oBACa;CACb,QAAQ,UAAU,UAAU;EACxB,mBAAmB,UAAU,GAAG,cAAc,KAAK,IAAI,YAAY;EAEnE,IAAI,MAAM,WAAW,SAAS,cAC1B,mBACI,UACA,GAAG,qBAAqB,MAAM,UAAU,IAAI,YAChD;CAER;AACJ"}
@@ -23,9 +23,26 @@ type LoggerConsole = Readonly<{
23
23
  error: (...args: readonly unknown[]) => void;
24
24
  log: (...args: readonly unknown[]) => void;
25
25
  }>;
26
+ /** One log call that passed the level threshold. */
27
+ type LogEntry = Readonly<{
28
+ args: readonly unknown[];
29
+ epochMilliseconds: number;
30
+ level: LogLevel;
31
+ loggerName: string;
32
+ message: string;
33
+ openTelemetryContext: OpenTelemetryContext;
34
+ /** The minimized stack trace, or `""` when the call has none. */
35
+ stackTrace: string;
36
+ }>;
37
+ /** A logger's resolved output options, the same for every call. */
38
+ type LogOutput = Readonly<{
39
+ logFilePath: string;
40
+ timestampFormat: TimestampFormat;
41
+ valueColorMode: ValueColorMode;
42
+ writeToFile: boolean;
43
+ }>;
44
+ type LogWriter = (entry: LogEntry, output: LogOutput) => void;
26
45
  type LoggerRuntime = Readonly<{
27
- appendTextFileSync?: (filePath: string, content: string) => void;
28
- console: LoggerConsole;
29
46
  /**
30
47
  * Reads the environment (NO_COLOR, FORCE_COLOR, SIMPLELOG_TIMESTAMP,
31
48
  * whether stdout is a terminal) once per logger, when it is constructed.
@@ -33,6 +50,12 @@ type LoggerRuntime = Readonly<{
33
50
  * {@link FALLBACK_CONSOLE_DEFAULTS}.
34
51
  */
35
52
  readConsoleDefaults?: () => ConsoleDefaults;
53
+ /**
54
+ * Formats and prints one entry. All output code sits behind it, so an entry
55
+ * bundles only the writer it uses: the browser gets neither the text
56
+ * formatting (`./console_text`) nor the log file (`./log_file`).
57
+ */
58
+ write: LogWriter;
36
59
  }>;
37
60
  type LoggerParent = Readonly<{
38
61
  getFullLoggerName: () => string;
@@ -40,6 +63,8 @@ type LoggerParent = Readonly<{
40
63
  }>;
41
64
  type LoggerConstructor = new (name: string, parent?: LoggerParent, options?: LoggerOptions) => LoggerBase;
42
65
  declare function createLoggerConsole(): LoggerConsole;
66
+ declare function buildLogMessage(timestamp: string, levelLabel: string, loggerName: string, openTelemetryContextLabel: string, message: string): string;
67
+ declare function formatOpenTelemetryContextLabel(openTelemetryContext?: OpenTelemetryContext): string;
43
68
  /**
44
69
  * Reads the active span, when something has registered a reader.
45
70
  *
@@ -57,16 +82,13 @@ type SpanContextReader = () => OpenTelemetryContext;
57
82
  declare function setSpanContextReader(reader?: SpanContextReader): void;
58
83
  declare class LoggerBase {
59
84
  private readonly LoggerConstructor;
60
- private readonly logFilePath;
85
+ private readonly includeOpenTelemetryContext;
61
86
  private readonly logLevelThreshold;
62
87
  private readonly name;
88
+ private readonly output;
63
89
  private readonly parent?;
64
90
  private readonly performanceBenchmarks;
65
91
  private readonly runtime;
66
- private readonly includeOpenTelemetryContext;
67
- private readonly timestampFormat;
68
- private readonly valueColorMode;
69
- private readonly writeToFile;
70
92
  protected constructor(LoggerConstructor: LoggerConstructor, runtime: LoggerRuntime, name: string, parent?: LoggerParent, options?: LoggerOptions);
71
93
  assert(condition: boolean, message: string, ...args: readonly unknown[]): void;
72
94
  createChildLogger(name: string, otherLogger?: LoggerParent): LoggerBase;
@@ -79,9 +101,7 @@ declare class LoggerBase {
79
101
  startPerformanceBenchmark(label: string): void;
80
102
  warn(message: string, ...args: readonly unknown[]): void;
81
103
  private log;
82
- private logStackTrace;
83
- private emitPayload;
84
104
  private mergeLoggers;
85
105
  }
86
- export { type ConsoleDefaults, type LogLevel, LoggerBase, type LoggerConsole, type LoggerConstructor, type LoggerOptions, type LoggerParent, type LoggerRuntime, type OpenTelemetryContext, type SpanContextReader, type TimestampFormat, type ValueColorMode, createLoggerConsole, setSpanContextReader };
106
+ export { type ConsoleDefaults, type LogEntry, type LogLevel, type LogOutput, type LogWriter, LoggerBase, type LoggerConsole, type LoggerConstructor, type LoggerOptions, type LoggerParent, type LoggerRuntime, type OpenTelemetryContext, type SpanContextReader, type TimestampFormat, type ValueColorMode, buildLogMessage, createLoggerConsole, formatOpenTelemetryContextLabel, setSpanContextReader };
87
107
  //# sourceMappingURL=logger_factory.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"logger_factory.d.ts","names":[],"sources":["../src/logger_factory.ts"],"mappings":";KAkCK;KAEA,uBAAuB;EACxB;EACA;;KAGC;KAEA,gBAAgB;EACjB;EACA;EACA,oBAAoB;;EAEpB,kBAAkB;EAClB,iBAAiB;EACjB;;;KAIC,kBAAkB;EACnB,iBAAiB;EACjB,gBAAgB;;KAGf,gBAAgB;EACjB,WAAW;EACX,SAAS;;KAGR,gBAAgB;EACjB,sBAAsB,kBAAkB;EACxC,SAAS;;;;;;;EAOT,4BAA4B;;KAG3B,eAAe;EAChB;EACA,2BAA2B;;KAG1B,yBACD,cACA,SAAS,cACT,UAAU,kBACT;iBA+DI,uBAAuB;;;;;;;;;;;;;;KAgc3B,0BAA0B;iBAgBtB,qBAAqB,SAAS;cA8JjC;mBACe;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;YAER,YACL,mBAAmB,mBACnB,SAAS,eACT,cACA,SAAS,cACT,UAAS;EAiBN,OACH,oBACA,oBACG;EAgBA,kBACH,cACA,cAAc,eACf;EAgBI,MAAM,oBAAoB;EAI1B,wBAAwB,eAAe;EAgBvC,MAAM,oBAAoB;EAI1B;EAQA,uBAAuB;EAWvB,KAAK,oBAAoB;EAIzB,0BAA0B;EAI1B,KAAK,oBAAoB;UAIxB;UAwBA;UAiBA;UAcA"}
1
+ {"version":3,"file":"logger_factory.d.ts","names":[],"sources":["../src/logger_factory.ts"],"mappings":";KAgBK;KAEA,uBAAuB;EACxB;EACA;;KAGC;KAEA,gBAAgB;EACjB;EACA;EACA,oBAAoB;;EAEpB,kBAAkB;EAClB,iBAAiB;EACjB;;;KAIC,kBAAkB;EACnB,iBAAiB;EACjB,gBAAgB;;KAGf,gBAAgB;EACjB,WAAW;EACX,SAAS;;;KAIR,WAAW;EACZ;EACA;EACA,OAAO;EACP;EACA;EACA,sBAAsB;;EAEtB;;;KAIC,YAAY;EACb;EACA,iBAAiB;EACjB,gBAAgB;EAChB;;KAGC,aAAa,OAAO,UAAU,QAAQ;KAEtC,gBAAgB;;;;;;;EAOjB,4BAA4B;;;;;;EAM5B,OAAO;;KAGN,eAAe;EAChB;EACA,2BAA2B;;KAG1B,yBACD,cACA,SAAS,cACT,UAAU,kBACT;iBASI,uBAAuB;iBAmFvB,gBACL,mBACA,oBACA,oBACA,mCACA;iBAKK,gCACL,uBAAuB;;;;;;;;;;;;;;KA0BtB,0BAA0B;iBAgBtB,qBAAqB,SAAS;cA+BjC;mBACe;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;YAER,YACL,mBAAmB,mBACnB,SAAS,eACT,cACA,SAAS,cACT,UAAS;EAYN,OACH,oBACA,oBACG;EAgBA,kBACH,cACA,cAAc,eACf;EAgBI,MAAM,oBAAoB;EAI1B,wBAAwB,eAAe;EAgBvC,MAAM,oBAAoB;EAI1B;EAQA,uBAAuB;EAQvB,KAAK,oBAAoB;EAIzB,0BAA0B;EAI1B,KAAK,oBAAoB;UAIxB;UA0BA"}