@murky-web/simplelog 2.0.1 → 3.0.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.
Files changed (40) hide show
  1. package/README.md +125 -15
  2. package/dist/bun_logger.d.ts +0 -2
  3. package/dist/bun_logger.d.ts.map +1 -1
  4. package/dist/bun_logger.js +1 -2
  5. package/dist/bun_logger.js.map +1 -1
  6. package/dist/console_defaults.js +45 -0
  7. package/dist/console_defaults.js.map +1 -0
  8. package/dist/console_timestamp.d.ts +4 -0
  9. package/dist/console_timestamp.d.ts.map +1 -0
  10. package/dist/console_timestamp.js +22 -0
  11. package/dist/console_timestamp.js.map +1 -0
  12. package/dist/hono_middleware.d.ts +14 -4
  13. package/dist/hono_middleware.d.ts.map +1 -1
  14. package/dist/hono_middleware.js +45 -20
  15. package/dist/hono_middleware.js.map +1 -1
  16. package/dist/logger.d.ts +0 -2
  17. package/dist/logger.d.ts.map +1 -1
  18. package/dist/logger.js +1 -2
  19. package/dist/logger.js.map +1 -1
  20. package/dist/logger_factory.d.ts +17 -3
  21. package/dist/logger_factory.d.ts.map +1 -1
  22. package/dist/logger_factory.js +66 -31
  23. package/dist/logger_factory.js.map +1 -1
  24. package/dist/node_runtime.js +14 -4
  25. package/dist/node_runtime.js.map +1 -1
  26. package/dist/otel.d.ts +0 -2
  27. package/dist/otel.d.ts.map +1 -1
  28. package/dist/otel.js +2 -3
  29. package/dist/serialize_value.js +313 -0
  30. package/dist/serialize_value.js.map +1 -0
  31. package/dist/web_logger.d.ts +0 -2
  32. package/dist/web_logger.d.ts.map +1 -1
  33. package/dist/web_logger.js +1 -2
  34. package/dist/web_logger.js.map +1 -1
  35. package/oxlint/prefer-runtime-entry.mjs +1 -1
  36. package/package.json +9 -11
  37. package/dist/deno_logger.d.ts +0 -8
  38. package/dist/deno_logger.d.ts.map +0 -1
  39. package/dist/deno_logger.js +0 -39
  40. package/dist/deno_logger.js.map +0 -1
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # SimpleLog
2
2
 
3
- `SimpleLog` is a lightweight and flexible logging utility for Node.js, Bun,
4
- Deno, and fetch-style edge runtimes. It provides various log levels, performance
3
+ `SimpleLog` is a lightweight and flexible logging utility for Node.js, Bun and
4
+ fetch-style edge runtimes. It provides various log levels, performance
5
5
  benchmarking, and the ability to log messages to both the console and a file.
6
6
 
7
7
  ## Features
@@ -43,12 +43,6 @@ Bun:
43
43
  import { Logger } from "@murky-web/simplelog/bun";
44
44
  ```
45
45
 
46
- Deno:
47
-
48
- ```typescript
49
- import { Logger } from "@murky-web/simplelog/deno";
50
- ```
51
-
52
46
  Web and edge runtimes:
53
47
 
54
48
  ```typescript
@@ -91,21 +85,108 @@ childLogger.info("This is a message from the child logger");
91
85
  - `logFilePath`: Path to the log file.
92
86
  - `logLevelThreshold`: Minimum log level for logging.
93
87
  - `valueColorMode`: `"level" | "syntax" | "off"` for console value coloring.
88
+ - `timestampFormat`: `"iso" | "time"` for the console timestamp.
94
89
  - `includeOpenTelemetryContext`: Adds active `trace_id` and `span_id` to each
95
90
  log line when an OpenTelemetry span is active.
96
91
 
97
92
  `valueColorMode` modes:
98
93
 
99
- - `level`: current default, all console pieces use the log-level color
94
+ - `level`: all console pieces use the log-level color
100
95
  - `syntax`: extra values use type-based colors like strings, numbers, booleans,
101
96
  nullish values, symbols, and objects
102
97
  - `off`: console output stays plain
103
98
 
99
+ `timestampFormat` modes:
100
+
101
+ - `iso`: the full UTC timestamp, `2026-11-19T16:59:23.745Z`
102
+ - `time`: the local time of day, `16:59:23.745`
103
+
104
+ ### Defaults for colors and timestamps
105
+
106
+ Without the option, the Node and Bun entries pick both from the environment when
107
+ a logger is created. Child loggers inherit the parent's values.
108
+
109
+ Colors (`valueColorMode`), `NO_COLOR` as https://no-color.org defines it plus
110
+ Node's `FORCE_COLOR` values:
111
+
112
+ 1. `NO_COLOR` set and not empty: `"off"`.
113
+ 2. `FORCE_COLOR` set: `"level"`, even when empty, except `FORCE_COLOR=0` or
114
+ `false`, which means `"off"`.
115
+ 3. Otherwise `"level"` when stdout is a terminal, `"off"` when it is a pipe or a
116
+ file (CI, systemd, Docker, a process manager).
117
+
118
+ The check looks at stdout only. Stack traces of `error()` and `assert()` go to
119
+ stderr with the same colors, so `app 2>errors.log` in a terminal writes ANSI
120
+ codes into `errors.log`; set `NO_COLOR=1` there.
121
+
122
+ Timestamp (`timestampFormat`):
123
+
124
+ 1. `SIMPLELOG_TIMESTAMP=time` or `SIMPLELOG_TIMESTAMP=iso`.
125
+ 2. Otherwise `"time"` when stdout is a terminal, `"iso"` when it is not.
126
+
127
+ Set `SIMPLELOG_TIMESTAMP=time` for output that goes through a pipe but is read
128
+ by people, for example a process manager's terminal UI.
129
+
130
+ An explicit option always wins over the environment. Log files always get the
131
+ ISO timestamp and never colors, whatever the console shows. The `web` entry has
132
+ no terminal to ask: it keeps `"level"` and `"iso"`.
133
+
104
134
  `includeOpenTelemetryContext` is intentionally opt-in. When enabled, `simplelog`
105
135
  reads the current active span from `@opentelemetry/api` and appends `trace_id`
106
136
  and `span_id` to console and file output. It does not install an OpenTelemetry
107
137
  SDK or exporter for you.
108
138
 
139
+ ## Output Format
140
+
141
+ ### File lines
142
+
143
+ A log file entry is the console line without colors: ISO timestamp, level,
144
+ logger name, message, then every additional argument separated by a space.
145
+ Objects are written as compact, single-line JSON (the console keeps the indented
146
+ form), so one entry is one line.
147
+
148
+ Control characters, the Unicode line and paragraph separators (U+2028, U+2029),
149
+ the bidirectional controls (U+200E, U+200F, U+061C, U+202A to U+202E, U+2066 to
150
+ U+2069) and the byte order mark (U+FEFF) in the message, the logger name and the
151
+ arguments are written as `\n`, `\r` or `\uXXXX`. A value cannot start a line of
152
+ its own or disguise one. Tab and backslash are left alone (escaping backslashes
153
+ would mangle Windows paths), so the file is readable text, not an encoding you
154
+ can reverse unambiguously.
155
+
156
+ A stack trace is written after its entry as continuation lines, each starting
157
+ with a tab. Every entry starts with a timestamp, never with a tab.
158
+
159
+ ### How arguments are printed
160
+
161
+ - An `Error` prints only `name`, `message`, `stack`, `cause`, `code` when it is
162
+ a string or a number, and, for an `AggregateError`, `errors`. All other
163
+ properties are left out on purpose: HTTP client errors (axios, got) carry the
164
+ request, its headers and its body there.
165
+ - Inside an Error, `cause` and the elements of `errors` print in full only when
166
+ they are Errors themselves (same rules, recursively). Primitives print as they
167
+ are. Any other object prints as `"[Object]"`, because a `cause` is often an
168
+ HTTP response or request with credentials in it.
169
+ - `Map` prints as `{ "Map": [[key, value]] }`, `Set` as `{ "Set": [value] }`,
170
+ `BigInt` as `"123n"`, a function as `"[Function name]"`, `String`, `Number`
171
+ and `Boolean` objects as their primitive value.
172
+ - Typed arrays, `DataView` and `ArrayBuffer` print as a label with their byte
173
+ length, for example `"[Uint8Array 5000000 bytes]"`. Their contents are not
174
+ printed.
175
+ - Cycles print as `"[Circular]"`, nesting deeper than 8 levels as
176
+ `"[MaxDepth]"`.
177
+ - A call prints at most 1000 values per argument, and 50 keys per object and 50
178
+ items per array, `Map` or `Set`. What is left out is shown as `"[Truncated]"`
179
+ (an object gets a `"[Truncated]": <omitted keys>` entry).
180
+ - Arrays, `Map` and `Set` are not walked past the 50th item: the omitted count
181
+ comes from `length` or `size`, so even a sparse array of length 2^32 - 1 is
182
+ cheap. An object's key list is built in full before the first 50 are kept
183
+ (JavaScript has no way to stop that early), so an object with millions of keys
184
+ costs one pass over its keys, but none of its values are serialized.
185
+
186
+ simplelog does not look for secrets. Tokens, passwords or personal data you put
187
+ in a message or in an argument are written as they are; redacting them is up to
188
+ the caller.
189
+
109
190
  ## Log Levels
110
191
 
111
192
  - `DEBUG`: Detailed information, typically of interest only when diagnosing
@@ -121,7 +202,6 @@ SDK or exporter for you.
121
202
  - `@murky-web/simplelog`: Node-first default entry
122
203
  - `@murky-web/simplelog/node`: explicit Node entry
123
204
  - `@murky-web/simplelog/bun`: Bun entry
124
- - `@murky-web/simplelog/deno`: Deno entry
125
205
  - `@murky-web/simplelog/web`: runtime-neutral console logger for fetch-style
126
206
  runtimes
127
207
  - `@murky-web/simplelog/hono`: Hono middleware for request-scoped logging
@@ -136,10 +216,9 @@ For Hono-based servers and metaframeworks, prefer the runtime-neutral `web`
136
216
  logger together with the Hono middleware entry:
137
217
 
138
218
  ```typescript
139
- import { Hono } from "hono";
140
-
141
219
  import { createHonoLoggerMiddleware } from "@murky-web/simplelog/hono";
142
220
  import { Logger } from "@murky-web/simplelog/web";
221
+ import { Hono } from "hono";
143
222
 
144
223
  type AppVariables = {
145
224
  logger: Logger;
@@ -162,11 +241,22 @@ app.get("/", (c) => {
162
241
  The middleware exposes `c.var.logger`, and it logs request completion with
163
242
  method, path, status, duration, request ID, and Hono's runtime key.
164
243
 
244
+ The query string is not logged: query strings often carry tokens, OAuth codes
245
+ and e-mail addresses. If you need it, opt in with `includeQuery: true`; it then
246
+ appears as a separate `query` field (`"?q=cats&page=2"`) next to `path`:
247
+
248
+ ```typescript
249
+ app.use(createHonoLoggerMiddleware({ logger, includeQuery: true }));
250
+ ```
251
+
252
+ `hono` is an optional peer dependency. Only the `@murky-web/simplelog/hono`
253
+ entry imports it, so you need it installed only when you use the middleware.
254
+
165
255
  This adapter is intentionally thin:
166
256
 
167
257
  - it uses Hono's middleware and request context model
168
258
  - it creates a request-scoped child logger
169
- - it works across Node, Bun, Deno, Cloudflare, and Netlify style runtimes
259
+ - it works across Node, Bun, Cloudflare, and Netlify style runtimes
170
260
  - it does not own your tracing SDK or framework-specific SSR handoff
171
261
 
172
262
  If you want a custom request logger name, you can provide one directly or
@@ -183,6 +273,12 @@ app.use(
183
273
  );
184
274
  ```
185
275
 
276
+ The `context` has `method`, `path`, `query` (the query string with its leading
277
+ `?`, or `""`), `requestId`, `runtime` and `url`. The middleware itself logs
278
+ `query` only with `includeQuery: true`; a name you build from `context.query` or
279
+ `context.url` puts the query string into the log, so leave it out unless you
280
+ want that.
281
+
186
282
  ## Oxlint Integration
187
283
 
188
284
  `@murky-web/simplelog/oxlint` exports the SimpleLog-specific Oxlint JS plugin.
@@ -197,8 +293,22 @@ Current rules:
197
293
  - `simplelog/prefer-runtime-entry`
198
294
  - `simplelog/require-logger-name`
199
295
 
200
- If you use `@murky-web/config`, running `web-dev-config init --oxc --simplelog`
201
- wires this preset automatically.
296
+ Enable the plugin and the rules in your `.oxlintrc.jsonc`:
297
+
298
+ ```jsonc
299
+ {
300
+ "jsPlugins": ["@murky-web/simplelog/oxlint"],
301
+ "rules": {
302
+ "simplelog/prefer-simplelog": "error",
303
+ "simplelog/prefer-child-logger": "error",
304
+ "simplelog/no-ad-hoc-console-fallback": "error",
305
+ "simplelog/no-console-alias": "error",
306
+ "simplelog/prefer-hono-context-logger": "error",
307
+ "simplelog/prefer-runtime-entry": "error",
308
+ "simplelog/require-logger-name": "error",
309
+ },
310
+ }
311
+ ```
202
312
 
203
313
  ## OpenTelemetry Integration
204
314
 
@@ -1,8 +1,6 @@
1
1
  import { LogLevel, LoggerBase, LoggerOptions, LoggerParent } from "./logger_factory.js";
2
- //#region src/bun_logger.d.ts
3
2
  declare class Logger extends LoggerBase {
4
3
  constructor(name: string, parent?: LoggerParent, options?: LoggerOptions);
5
4
  }
6
- //#endregion
7
5
  export { type LogLevel, Logger, type LoggerOptions };
8
6
  //# sourceMappingURL=bun_logger.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"bun_logger.d.ts","names":[],"sources":["../src/bun_logger.ts"],"mappings":";;cAIM,eAAe;EACnB,YACE,cACA,SAAS,cACT,UAAS"}
1
+ {"version":3,"file":"bun_logger.d.ts","names":[],"sources":["../src/bun_logger.ts"],"mappings":";cAIM,eAAe;EACjB,YACI,cACA,SAAS,cACT,UAAS"}
@@ -1,12 +1,11 @@
1
1
  import { LoggerBase } from "./logger_factory.js";
2
2
  import { nodeRuntime } from "./node_runtime.js";
3
- //#region src/bun_logger.ts
3
+ // src/bun_logger.ts
4
4
  var Logger = class Logger extends LoggerBase {
5
5
  constructor(name, parent, options = {}) {
6
6
  super(Logger, nodeRuntime, name, parent, options);
7
7
  }
8
8
  };
9
- //#endregion
10
9
  export { Logger };
11
10
 
12
11
  //# sourceMappingURL=bun_logger.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"bun_logger.js","names":["bunRuntime"],"sources":["../src/bun_logger.ts"],"sourcesContent":["import { nodeRuntime as bunRuntime } from \"./node_runtime\";\nimport { LoggerBase } from \"./logger_factory\";\nimport type { LoggerOptions, LoggerParent, LogLevel } from \"./logger_factory\";\n\nclass Logger extends LoggerBase {\n constructor(\n name: string,\n parent?: LoggerParent,\n options: LoggerOptions = {},\n ) {\n super(Logger, bunRuntime, name, parent, options);\n }\n}\n\nexport { Logger };\n\nexport type { LoggerOptions, LogLevel };\n"],"mappings":";;;AAIA,IAAM,SAAN,MAAM,eAAe,WAAW;CAC9B,YACE,MACA,QACA,UAAyB,CAAC,GAC1B;EACA,MAAM,QAAQA,aAAY,MAAM,QAAQ,OAAO;CACjD;AACF"}
1
+ {"version":3,"file":"bun_logger.js","names":["bunRuntime"],"sources":["../src/bun_logger.ts"],"sourcesContent":["import { LoggerBase } from \"./logger_factory\";\nimport type { LoggerOptions, LoggerParent, LogLevel } from \"./logger_factory\";\nimport { nodeRuntime as bunRuntime } from \"./node_runtime\";\n\nclass Logger extends LoggerBase {\n constructor(\n name: string,\n parent?: LoggerParent,\n options: LoggerOptions = {},\n ) {\n super(Logger, bunRuntime, name, parent, options);\n }\n}\n\nexport { Logger };\n\nexport type { LoggerOptions, LogLevel };\n"],"mappings":";;;AAIA,IAAM,SAAN,MAAM,eAAe,WAAW;CAC5B,YACI,MACA,QACA,UAAyB,CAAC,GAC5B;EACE,MAAM,QAAQA,aAAY,MAAM,QAAQ,OAAO;CACnD;AACJ"}
@@ -0,0 +1,45 @@
1
+ // src/console_defaults.ts
2
+ const FORCE_COLOR_DISABLED = /* @__PURE__ */ new Set(["0", "false"]);
3
+ /**
4
+ * `NO_COLOR` as https://no-color.org defines it wins, then `FORCE_COLOR` with
5
+ * Node's values (`0` and `false` mean off, anything else, even empty, means
6
+ * on), then whether stdout is a terminal.
7
+ *
8
+ * @param {ConsoleEnvironment} environment - The raw environment.
9
+ * @returns {ValueColorMode} `"level"` for colors, `"off"` for plain text.
10
+ */
11
+ function resolveDefaultValueColorMode(environment) {
12
+ if (typeof environment.noColor === "string" && environment.noColor !== "") return "off";
13
+ if (typeof environment.forceColor === "string") {
14
+ if (FORCE_COLOR_DISABLED.has(environment.forceColor)) return "off";
15
+ return "level";
16
+ }
17
+ if (environment.stdoutIsTerminal) return "level";
18
+ return "off";
19
+ }
20
+ function parseTimestampFormat(value) {
21
+ if (value === "iso" || value === "time") return value;
22
+ }
23
+ /**
24
+ * The time of day is enough to read along in a terminal; a pipe usually ends in
25
+ * a file, CI or a log service, where the date is needed. `SIMPLELOG_TIMESTAMP`
26
+ * overrides that for pipes that are read by people (a process manager's TUI).
27
+ *
28
+ * @param {ConsoleEnvironment} environment - The raw environment.
29
+ * @returns {TimestampFormat} The console timestamp format.
30
+ */
31
+ function resolveDefaultTimestampFormat(environment) {
32
+ const override = parseTimestampFormat(environment.simplelogTimestamp);
33
+ if (override !== void 0) return override;
34
+ if (environment.stdoutIsTerminal) return "time";
35
+ return "iso";
36
+ }
37
+ function resolveConsoleDefaults(environment) {
38
+ return {
39
+ timestampFormat: resolveDefaultTimestampFormat(environment),
40
+ valueColorMode: resolveDefaultValueColorMode(environment)
41
+ };
42
+ }
43
+ export { resolveConsoleDefaults };
44
+
45
+ //# sourceMappingURL=console_defaults.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"console_defaults.js","names":[],"sources":["../src/console_defaults.ts"],"sourcesContent":["import type {\n ConsoleDefaults,\n TimestampFormat,\n ValueColorMode,\n} from \"./logger_factory\";\n\n/**\n * What a runtime knows about where its console output goes, read raw from the\n * environment. The Node and Bun runtime fills it in; this module turns it into\n * defaults and never touches `process` itself, so it stays safe for the browser\n * build.\n */\ntype ConsoleEnvironment = Readonly<{\n forceColor: string | undefined;\n noColor: string | undefined;\n simplelogTimestamp: string | undefined;\n stdoutIsTerminal: boolean;\n}>;\n\nconst FORCE_COLOR_DISABLED = new Set([\"0\", \"false\"]);\n\n/**\n * `NO_COLOR` as https://no-color.org defines it wins, then `FORCE_COLOR` with\n * Node's values (`0` and `false` mean off, anything else, even empty, means\n * on), then whether stdout is a terminal.\n *\n * @param {ConsoleEnvironment} environment - The raw environment.\n * @returns {ValueColorMode} `\"level\"` for colors, `\"off\"` for plain text.\n */\nfunction resolveDefaultValueColorMode(\n environment: ConsoleEnvironment,\n): ValueColorMode {\n if (typeof environment.noColor === \"string\" && environment.noColor !== \"\") {\n return \"off\";\n }\n\n if (typeof environment.forceColor === \"string\") {\n if (FORCE_COLOR_DISABLED.has(environment.forceColor)) {\n return \"off\";\n }\n\n return \"level\";\n }\n\n if (environment.stdoutIsTerminal) {\n return \"level\";\n }\n\n return \"off\";\n}\n\nfunction parseTimestampFormat(\n value: string | undefined,\n): TimestampFormat | undefined {\n if (value === \"iso\" || value === \"time\") {\n return value;\n }\n\n return undefined;\n}\n\n/**\n * The time of day is enough to read along in a terminal; a pipe usually ends in\n * a file, CI or a log service, where the date is needed. `SIMPLELOG_TIMESTAMP`\n * overrides that for pipes that are read by people (a process manager's TUI).\n *\n * @param {ConsoleEnvironment} environment - The raw environment.\n * @returns {TimestampFormat} The console timestamp format.\n */\nfunction resolveDefaultTimestampFormat(\n environment: ConsoleEnvironment,\n): TimestampFormat {\n const override = parseTimestampFormat(environment.simplelogTimestamp);\n\n if (override !== undefined) {\n return override;\n }\n\n if (environment.stdoutIsTerminal) {\n return \"time\";\n }\n\n return \"iso\";\n}\n\nfunction resolveConsoleDefaults(\n environment: ConsoleEnvironment,\n): ConsoleDefaults {\n return {\n timestampFormat: resolveDefaultTimestampFormat(environment),\n valueColorMode: resolveDefaultValueColorMode(environment),\n };\n}\n\nexport { resolveConsoleDefaults };\nexport type { ConsoleEnvironment };\n"],"mappings":";AAmBA,MAAM,uCAAuB,IAAI,IAAI,CAAC,KAAK,OAAO,CAAC;;;;;;;;;AAUnD,SAAS,6BACL,aACc;CACd,IAAI,OAAO,YAAY,YAAY,YAAY,YAAY,YAAY,IACnE,OAAO;CAGX,IAAI,OAAO,YAAY,eAAe,UAAU;EAC5C,IAAI,qBAAqB,IAAI,YAAY,UAAU,GAC/C,OAAO;EAGX,OAAO;CACX;CAEA,IAAI,YAAY,kBACZ,OAAO;CAGX,OAAO;AACX;AAEA,SAAS,qBACL,OAC2B;CAC3B,IAAI,UAAU,SAAS,UAAU,QAC7B,OAAO;AAIf;;;;;;;;;AAUA,SAAS,8BACL,aACe;CACf,MAAM,WAAW,qBAAqB,YAAY,kBAAkB;CAEpE,IAAI,aAAa,KAAA,GACb,OAAO;CAGX,IAAI,YAAY,kBACZ,OAAO;CAGX,OAAO;AACX;AAEA,SAAS,uBACL,aACe;CACf,OAAO;EACH,iBAAiB,8BAA8B,WAAW;EAC1D,gBAAgB,6BAA6B,WAAW;CAC5D;AACJ"}
@@ -0,0 +1,4 @@
1
+ /** `"iso"`: `2026-11-19T16:59:23.745Z`; `"time"`: local `16:59:23.745`. */
2
+ type TimestampFormat = "iso" | "time";
3
+ export type { TimestampFormat };
4
+ //# sourceMappingURL=console_timestamp.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"console_timestamp.d.ts","names":[],"sources":["../src/console_timestamp.ts"],"mappings":";KACK"}
@@ -0,0 +1,22 @@
1
+ // src/console_timestamp.ts
2
+ const TIME_PART_WIDTH = 2;
3
+ const MILLISECONDS_WIDTH = 3;
4
+ function padTimePart(value, width = TIME_PART_WIDTH) {
5
+ return `${value}`.padStart(width, "0");
6
+ }
7
+ /**
8
+ * `"time"` is the local time of day, the clock a developer reads the log
9
+ * against.
10
+ *
11
+ * @param {number} epochMilliseconds - The moment of the log call.
12
+ * @param {TimestampFormat} format - The console timestamp format.
13
+ * @returns {string} `16:59:23.745` for `"time"`, the ISO string for `"iso"`.
14
+ */
15
+ function formatConsoleTimestamp(epochMilliseconds, format) {
16
+ const date = new Date(epochMilliseconds);
17
+ if (format === "iso") return date.toISOString();
18
+ return `${padTimePart(date.getHours())}:${padTimePart(date.getMinutes())}:${padTimePart(date.getSeconds())}.${padTimePart(date.getMilliseconds(), MILLISECONDS_WIDTH)}`;
19
+ }
20
+ export { formatConsoleTimestamp };
21
+
22
+ //# sourceMappingURL=console_timestamp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"console_timestamp.js","names":[],"sources":["../src/console_timestamp.ts"],"sourcesContent":["/** `\"iso\"`: `2026-11-19T16:59:23.745Z`; `\"time\"`: local `16:59:23.745`. */\ntype TimestampFormat = \"iso\" | \"time\";\n\nconst TIME_PART_WIDTH = 2;\nconst MILLISECONDS_WIDTH = 3;\n\nfunction padTimePart(value: number, width = TIME_PART_WIDTH): string {\n return `${value}`.padStart(width, \"0\");\n}\n\n/**\n * `\"time\"` is the local time of day, the clock a developer reads the log\n * against.\n *\n * @param {number} epochMilliseconds - The moment of the log call.\n * @param {TimestampFormat} format - The console timestamp format.\n * @returns {string} `16:59:23.745` for `\"time\"`, the ISO string for `\"iso\"`.\n */\nfunction formatConsoleTimestamp(\n epochMilliseconds: number,\n format: TimestampFormat,\n): string {\n const date = new Date(epochMilliseconds);\n\n if (format === \"iso\") {\n return date.toISOString();\n }\n\n return `${padTimePart(date.getHours())}:${padTimePart(date.getMinutes())}:${padTimePart(date.getSeconds())}.${padTimePart(date.getMilliseconds(), MILLISECONDS_WIDTH)}`;\n}\n\nexport { formatConsoleTimestamp };\nexport type { TimestampFormat };\n"],"mappings":";AAGA,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAE3B,SAAS,YAAY,OAAe,QAAQ,iBAAyB;CACjE,OAAO,GAAG,QAAQ,SAAS,OAAO,GAAG;AACzC;;;;;;;;;AAUA,SAAS,uBACL,mBACA,QACM;CACN,MAAM,OAAO,IAAI,KAAK,iBAAiB;CAEvC,IAAI,WAAW,OACX,OAAO,KAAK,YAAY;CAG5B,OAAO,GAAG,YAAY,KAAK,SAAS,CAAC,EAAE,GAAG,YAAY,KAAK,WAAW,CAAC,EAAE,GAAG,YAAY,KAAK,WAAW,CAAC,EAAE,GAAG,YAAY,KAAK,gBAAgB,GAAG,kBAAkB;AACxK"}
@@ -1,7 +1,6 @@
1
- import { LoggerBase } from "./logger_factory.js";
2
- import { getRuntimeKey } from "hono/adapter";
3
1
  import { MiddlewareHandler } from "hono";
4
- //#region src/hono_middleware.d.ts
2
+ import { getRuntimeKey } from "hono/adapter";
3
+ import { LoggerBase } from "./logger_factory.js";
5
4
  type RequestRuntimeKey = ReturnType<typeof getRuntimeKey>;
6
5
  type HonoLoggerVariables = {
7
6
  logger: LoggerBase;
@@ -12,17 +11,28 @@ type HonoLoggerMiddleware = MiddlewareHandler<{
12
11
  type RequestLoggerContext = Readonly<{
13
12
  method: string;
14
13
  path: string;
14
+ /**
15
+ * The query string including the leading `?` (`"?a=1&b=2"`), or `""` when
16
+ * there is none. It is passed to `requestLoggerName` only; the middleware
17
+ * logs it as `query` just when `includeQuery` is on.
18
+ */
19
+ query: string;
15
20
  requestId: string;
16
21
  runtime: RequestRuntimeKey;
17
22
  url: string;
18
23
  }>;
19
24
  type RequestLoggerNameResolver = (context: RequestLoggerContext) => string;
20
25
  type HonoLoggerMiddlewareOptions = Readonly<{
26
+ /**
27
+ * Adds the request's query string (`?a=1&b=2`) to the logged metadata as
28
+ * `query`. Off by default: query strings often carry tokens, OAuth codes and
29
+ * e-mail addresses, and the log keeps only the path.
30
+ */
31
+ includeQuery?: boolean;
21
32
  logCompletedRequests?: boolean;
22
33
  logger: Readonly<LoggerBase>;
23
34
  requestLoggerName?: RequestLoggerNameResolver | string;
24
35
  }>;
25
36
  declare function createHonoLoggerMiddleware(options: HonoLoggerMiddlewareOptions): HonoLoggerMiddleware;
26
- //#endregion
27
37
  export { type HonoLoggerMiddlewareOptions, type HonoLoggerVariables, type RequestLoggerContext, createHonoLoggerMiddleware };
28
38
  //# sourceMappingURL=hono_middleware.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"hono_middleware.d.ts","names":[],"sources":["../src/hono_middleware.ts"],"mappings":";;;;KAaK,oBAAoB,kBAAkB;KAEtC;EACH,QAAQ;;KAGL,uBAAuB;EAC1B,WAAW;;KA+BR,uBAAuB;EAC1B;EACA;EACA;EACA,SAAS;EACT;;KAGG,6BAA6B,SAAS;KAEtC,8BAA8B;EACjC;EACA,QAAQ,SAAS;EACjB,oBAAoB;;iBAqMb,2BACP,SAAS,8BACR"}
1
+ {"version":3,"file":"hono_middleware.d.ts","names":[],"sources":["../src/hono_middleware.ts"],"mappings":";;;KAcK,oBAAoB,kBAAkB;KAEtC;EACD,QAAQ;;KAGP,uBAAuB;EACxB,WAAW;;KAmCV,uBAAuB;EACxB;EACA;;;;;;EAMA;EACA;EACA,SAAS;EACT;;KAGC,6BAA6B,SAAS;KAEtC,8BAA8B;;;;;;EAM/B;EACA;EACA,QAAQ,SAAS;EACjB,oBAAoB;;iBA0Pf,2BACL,SAAS,8BACV"}
@@ -1,21 +1,30 @@
1
1
  import { getRuntimeKey } from "hono/adapter";
2
2
  import { createMiddleware } from "hono/factory";
3
- //#region src/hono_middleware.ts
3
+ // src/hono_middleware.ts
4
4
  const DEFAULT_ERROR_STATUS = 500;
5
5
  const DEFAULT_REQUEST_LOGGER_NAME = "request";
6
6
  const EMPTY_REQUEST_ID = "";
7
7
  const FAILED_REQUEST_MESSAGE = "Request failed";
8
8
  const REQUEST_COMPLETED_MESSAGE = "Request completed";
9
9
  const REQUEST_ID_HEADER = "x-request-id";
10
+ const EMPTY_QUERY = "";
10
11
  function resolveRequestId(c) {
11
12
  const requestId = c.req.header(REQUEST_ID_HEADER);
12
13
  if (typeof requestId !== "string" || requestId.length === 0) return EMPTY_REQUEST_ID;
13
14
  return requestId;
14
15
  }
16
+ function extractQuery(url) {
17
+ try {
18
+ return new URL(url).search;
19
+ } catch {
20
+ return EMPTY_QUERY;
21
+ }
22
+ }
15
23
  function createRequestLoggerContext(c) {
16
24
  return {
17
25
  method: c.req.method,
18
26
  path: c.req.path,
27
+ query: extractQuery(c.req.url),
19
28
  requestId: resolveRequestId(c),
20
29
  runtime: getRuntimeKey(),
21
30
  url: c.req.url
@@ -29,37 +38,50 @@ function resolveRequestLoggerName(requestLoggerContext, requestLoggerName) {
29
38
  function createRequestLogger(logger, requestLoggerContext, requestLoggerName) {
30
39
  return logger.createChildLogger(resolveRequestLoggerName(requestLoggerContext, requestLoggerName));
31
40
  }
41
+ function createRequestOnlyReader(c) {
42
+ return { req: {
43
+ header(name) {
44
+ return c.req.header(name);
45
+ },
46
+ method: c.req.method,
47
+ path: c.req.path,
48
+ url: c.req.url
49
+ } };
50
+ }
51
+ /**
52
+ * Reads the response status, so call it only after `next()`. Hono's `c.res`
53
+ * getter creates a placeholder Response on first access, and a handler's own
54
+ * Response is then copied into a new one (`new Response(body, res)`) when it is
55
+ * set. Touching `c.res` before the handler ran therefore replaces every
56
+ * response and loses its identity.
57
+ *
58
+ * @param {MiddlewareContext} c - The Hono context, after `next()` returned.
59
+ * @returns {RequestContextReader} The request, the error and the status.
60
+ */
32
61
  function createRequestReader(c) {
33
62
  return {
63
+ ...createRequestOnlyReader(c),
34
64
  error: c.error,
35
- req: {
36
- header(name) {
37
- return c.req.header(name);
38
- },
39
- method: c.req.method,
40
- path: c.req.path,
41
- url: c.req.url
42
- },
43
65
  res: { status: c.res.status }
44
66
  };
45
67
  }
46
68
  function createRequestLoggingState(c, options) {
47
- const requestLoggerContext = createRequestLoggerContext(createRequestReader(c));
69
+ const requestLoggerContext = createRequestLoggerContext(createRequestOnlyReader(c));
48
70
  return {
49
71
  requestLogger: createRequestLogger(options.logger, requestLoggerContext, options.requestLoggerName),
50
72
  requestLoggerContext,
51
73
  startTime: Date.now()
52
74
  };
53
75
  }
54
- function buildRequestMetadata(requestLoggerContext, durationMs, status) {
76
+ function buildRequestMetadata(requestLoggerContext, includeQuery, durationMs, status) {
55
77
  const requestMetadata = {
56
78
  durationMs,
57
79
  method: requestLoggerContext.method,
58
80
  path: requestLoggerContext.path,
59
81
  runtime: requestLoggerContext.runtime,
60
- status,
61
- url: requestLoggerContext.url
82
+ status
62
83
  };
84
+ if (includeQuery && requestLoggerContext.query.length > 0) requestMetadata.query = requestLoggerContext.query;
63
85
  if (requestLoggerContext.requestId.length > 0) requestMetadata.requestId = requestLoggerContext.requestId;
64
86
  return requestMetadata;
65
87
  }
@@ -81,20 +103,24 @@ function getElapsedMilliseconds(startTime) {
81
103
  function shouldLogCompletedRequests(logCompletedRequests) {
82
104
  return logCompletedRequests ?? true;
83
105
  }
84
- function logCompletedRequest(c, requestLogger, requestLoggerContext, startTime) {
85
- requestLogger.info(REQUEST_COMPLETED_MESSAGE, buildRequestMetadata(requestLoggerContext, getElapsedMilliseconds(startTime), c.res.status));
106
+ function shouldIncludeQuery(includeQuery) {
107
+ return includeQuery ?? false;
108
+ }
109
+ function logCompletedRequest(c, requestLogger, requestLoggerContext, includeQuery, startTime) {
110
+ requestLogger.info(REQUEST_COMPLETED_MESSAGE, buildRequestMetadata(requestLoggerContext, includeQuery, getElapsedMilliseconds(startTime), c.res.status));
86
111
  }
87
- function logFailedRequest(c, requestLogger, requestLoggerContext, startTime) {
88
- requestLogger.error(FAILED_REQUEST_MESSAGE, buildRequestMetadata(requestLoggerContext, getElapsedMilliseconds(startTime), c.res.status || DEFAULT_ERROR_STATUS), serializeThrownError(c.error));
112
+ function logFailedRequest(c, requestLogger, requestLoggerContext, includeQuery, startTime) {
113
+ requestLogger.error(FAILED_REQUEST_MESSAGE, buildRequestMetadata(requestLoggerContext, includeQuery, getElapsedMilliseconds(startTime), c.res.status || DEFAULT_ERROR_STATUS), serializeThrownError(c.error));
89
114
  }
90
115
  function finalizeRequestLogging(c, options, requestLoggingState) {
91
116
  const requestReader = createRequestReader(c);
117
+ const includeQuery = shouldIncludeQuery(options.includeQuery);
92
118
  if (typeof requestReader.error !== "undefined") {
93
- logFailedRequest(requestReader, requestLoggingState.requestLogger, requestLoggingState.requestLoggerContext, requestLoggingState.startTime);
119
+ logFailedRequest(requestReader, requestLoggingState.requestLogger, requestLoggingState.requestLoggerContext, includeQuery, requestLoggingState.startTime);
94
120
  return;
95
121
  }
96
122
  if (!shouldLogCompletedRequests(options.logCompletedRequests)) return;
97
- logCompletedRequest(requestReader, requestLoggingState.requestLogger, requestLoggingState.requestLoggerContext, requestLoggingState.startTime);
123
+ logCompletedRequest(requestReader, requestLoggingState.requestLogger, requestLoggingState.requestLoggerContext, includeQuery, requestLoggingState.startTime);
98
124
  }
99
125
  function createHonoLoggerMiddleware(options) {
100
126
  return createMiddleware(async (...[c, next]) => {
@@ -104,7 +130,6 @@ function createHonoLoggerMiddleware(options) {
104
130
  finalizeRequestLogging(c, options, requestLoggingState);
105
131
  });
106
132
  }
107
- //#endregion
108
133
  export { createHonoLoggerMiddleware };
109
134
 
110
135
  //# sourceMappingURL=hono_middleware.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"hono_middleware.js","names":[],"sources":["../src/hono_middleware.ts"],"sourcesContent":["import { getRuntimeKey } from \"hono/adapter\";\nimport { createMiddleware } from \"hono/factory\";\nimport type { MiddlewareHandler } from \"hono\";\n\nimport type { LoggerBase } from \"./logger_factory\";\n\nconst DEFAULT_ERROR_STATUS = 500;\nconst DEFAULT_REQUEST_LOGGER_NAME = \"request\";\nconst EMPTY_REQUEST_ID = \"\";\nconst FAILED_REQUEST_MESSAGE = \"Request failed\";\nconst REQUEST_COMPLETED_MESSAGE = \"Request completed\";\nconst REQUEST_ID_HEADER = \"x-request-id\";\n\ntype RequestRuntimeKey = ReturnType<typeof getRuntimeKey>;\n\ntype HonoLoggerVariables = {\n logger: LoggerBase;\n};\n\ntype HonoLoggerMiddleware = MiddlewareHandler<{\n Variables: HonoLoggerVariables;\n}>;\n\ntype RequestLike = Readonly<{\n header: (name: string) => string | undefined;\n method: string;\n path: string;\n url: string;\n}>;\n\ntype ResponseLike = Readonly<{\n status: number;\n}>;\n\ntype RequestContextReader = Readonly<{\n error?: unknown;\n req: RequestLike;\n res: ResponseLike;\n}>;\n\ntype MiddlewareContext = Readonly<{\n error?: unknown;\n req: RequestLike;\n res: ResponseLike;\n set: (key: \"logger\", value: Readonly<LoggerBase>) => void;\n}>;\n\ntype MiddlewareParameters = readonly [MiddlewareContext, () => Promise<void>];\n\ntype RequestMetadataValue = number | string;\n\ntype RequestLoggerContext = Readonly<{\n method: string;\n path: string;\n requestId: string;\n runtime: RequestRuntimeKey;\n url: string;\n}>;\n\ntype RequestLoggerNameResolver = (context: RequestLoggerContext) => string;\n\ntype HonoLoggerMiddlewareOptions = Readonly<{\n logCompletedRequests?: boolean;\n logger: Readonly<LoggerBase>;\n requestLoggerName?: RequestLoggerNameResolver | string;\n}>;\n\ntype RequestLoggingState = Readonly<{\n requestLogger: Readonly<LoggerBase>;\n requestLoggerContext: RequestLoggerContext;\n startTime: number;\n}>;\n\nfunction resolveRequestId(c: RequestContextReader): string {\n const requestId = c.req.header(REQUEST_ID_HEADER);\n\n if (typeof requestId !== \"string\" || requestId.length === EMPTY_REQUEST_ID.length) {\n return EMPTY_REQUEST_ID;\n }\n\n return requestId;\n}\n\nfunction createRequestLoggerContext(c: RequestContextReader): RequestLoggerContext {\n return {\n method: c.req.method,\n path: c.req.path,\n requestId: resolveRequestId(c),\n runtime: getRuntimeKey(),\n url: c.req.url,\n };\n}\n\nfunction resolveRequestLoggerName(\n requestLoggerContext: RequestLoggerContext,\n requestLoggerName: HonoLoggerMiddlewareOptions[\"requestLoggerName\"],\n): string {\n if (typeof requestLoggerName === \"function\") {\n return requestLoggerName(requestLoggerContext);\n }\n\n if (typeof requestLoggerName === \"string\") {\n return requestLoggerName;\n }\n\n return DEFAULT_REQUEST_LOGGER_NAME;\n}\n\nfunction createRequestLogger(\n logger: Readonly<LoggerBase>,\n requestLoggerContext: RequestLoggerContext,\n requestLoggerName: HonoLoggerMiddlewareOptions[\"requestLoggerName\"],\n): Readonly<LoggerBase> {\n return logger.createChildLogger(\n resolveRequestLoggerName(requestLoggerContext, requestLoggerName),\n );\n}\n\nfunction createRequestReader(c: MiddlewareContext): RequestContextReader {\n return {\n error: c.error,\n req: {\n header(name: string): string | undefined {\n return c.req.header(name);\n },\n method: c.req.method,\n path: c.req.path,\n url: c.req.url,\n },\n res: {\n status: c.res.status,\n },\n };\n}\n\nfunction createRequestLoggingState(\n c: MiddlewareContext,\n options: HonoLoggerMiddlewareOptions,\n): RequestLoggingState {\n const requestLoggerContext = createRequestLoggerContext(createRequestReader(c));\n\n return {\n requestLogger: createRequestLogger(\n options.logger,\n requestLoggerContext,\n options.requestLoggerName,\n ),\n requestLoggerContext,\n startTime: Date.now(),\n };\n}\n\nfunction buildRequestMetadata(\n requestLoggerContext: RequestLoggerContext,\n durationMs: number,\n status: number,\n): Readonly<Record<string, RequestMetadataValue>> {\n const requestMetadata: Record<string, RequestMetadataValue> = {\n durationMs,\n method: requestLoggerContext.method,\n path: requestLoggerContext.path,\n runtime: requestLoggerContext.runtime,\n status,\n url: requestLoggerContext.url,\n };\n\n if (requestLoggerContext.requestId.length > EMPTY_REQUEST_ID.length) {\n requestMetadata.requestId = requestLoggerContext.requestId;\n }\n\n return requestMetadata;\n}\n\nfunction serializeThrownError(error: unknown): Readonly<Record<string, string>> {\n if (error instanceof Error) {\n return {\n message: error.message,\n name: error.name,\n stack: error.stack ?? \"\",\n };\n }\n\n return {\n message: String(error),\n name: \"UnknownError\",\n stack: \"\",\n };\n}\n\nfunction getElapsedMilliseconds(startTime: number): number {\n return Date.now() - startTime;\n}\n\nfunction shouldLogCompletedRequests(\n logCompletedRequests: boolean | undefined,\n): boolean {\n return logCompletedRequests ?? true;\n}\n\nfunction logCompletedRequest(\n c: RequestContextReader,\n requestLogger: Readonly<LoggerBase>,\n requestLoggerContext: RequestLoggerContext,\n startTime: number,\n): void {\n requestLogger.info(\n REQUEST_COMPLETED_MESSAGE,\n buildRequestMetadata(\n requestLoggerContext,\n getElapsedMilliseconds(startTime),\n c.res.status,\n ),\n );\n}\n\nfunction logFailedRequest(\n c: RequestContextReader,\n requestLogger: Readonly<LoggerBase>,\n requestLoggerContext: RequestLoggerContext,\n startTime: number,\n): void {\n requestLogger.error(\n FAILED_REQUEST_MESSAGE,\n buildRequestMetadata(\n requestLoggerContext,\n getElapsedMilliseconds(startTime),\n c.res.status || DEFAULT_ERROR_STATUS,\n ),\n serializeThrownError(c.error),\n );\n}\n\nfunction finalizeRequestLogging(\n c: MiddlewareContext,\n options: HonoLoggerMiddlewareOptions,\n requestLoggingState: RequestLoggingState,\n): void {\n const requestReader = createRequestReader(c);\n\n if (typeof requestReader.error !== \"undefined\") {\n logFailedRequest(\n requestReader,\n requestLoggingState.requestLogger,\n requestLoggingState.requestLoggerContext,\n requestLoggingState.startTime,\n );\n return;\n }\n\n if (!shouldLogCompletedRequests(options.logCompletedRequests)) {\n return;\n }\n\n logCompletedRequest(\n requestReader,\n requestLoggingState.requestLogger,\n requestLoggingState.requestLoggerContext,\n requestLoggingState.startTime,\n );\n}\n\nfunction createHonoLoggerMiddleware(\n options: HonoLoggerMiddlewareOptions,\n): HonoLoggerMiddleware {\n return createMiddleware<{\n Variables: HonoLoggerVariables;\n }>(async (...[c, next]: MiddlewareParameters): Promise<void> => {\n const requestLoggingState = createRequestLoggingState(c, options);\n\n c.set(\"logger\", requestLoggingState.requestLogger);\n await next();\n finalizeRequestLogging(c, options, requestLoggingState);\n });\n}\n\nexport { createHonoLoggerMiddleware };\n\nexport type {\n HonoLoggerMiddlewareOptions,\n HonoLoggerVariables,\n RequestLoggerContext,\n};\n"],"mappings":";;;AAMA,MAAM,uBAAuB;AAC7B,MAAM,8BAA8B;AACpC,MAAM,mBAAmB;AACzB,MAAM,yBAAyB;AAC/B,MAAM,4BAA4B;AAClC,MAAM,oBAAoB;AA8D1B,SAAS,iBAAiB,GAAiC;CACzD,MAAM,YAAY,EAAE,IAAI,OAAO,iBAAiB;CAEhD,IAAI,OAAO,cAAc,YAAY,UAAU,WAAW,GACxD,OAAO;CAGT,OAAO;AACT;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AO,KAAK;EACrB,MAAM;EACN,OAAO;CACT;AACF;AAEA,SAAS,uBAAuB,WAA2B;CACzD,OAAO,KAAK,IAAI,IAAI;AACtB;AAEA,SAAS,2BACP,sBACS;CACT,OAAO,wBAAwB;AACjC;AAEA,SAAS,oBACP,GACA,eACA,sBACA,WACM;CACN,cAAc,KACZ,2BACA,qBACE,sBACA,uBAAuB,SAAS,GAChC,EAAE,IAAI,MACR,CACF;AACF;AAEA,SAAS,iBACP,GACA,eACA,sBACA,WACM;CACN,cAAc,MACZ,wBACA,qBACE,sBACA,uBAAuB,SAAS,GAChC,EAAE,IAAI,UAAU,oBAClB,GACA,qBAAqB,EAAE,KAAK,CAC9B;AACF;AAEA,SAAS,uBACP,GACA,SACA,qBACM;CACN,MAAM,gBAAgB,oBAAoB,CAAC;CAE3C,IAAI,OAAO,cAAc,UAAU,aAAa;EAC9C,iBACE,eACA,oBAAoB,eACpB,oBAAoB,sBACpB,oBAAoB,SACtB;EACA;CACF;CAEA,IAAI,CAAC,2BAA2B,QAAQ,oBAAoB,GAC1D;CAGF,oBACE,eACA,oBAAoB,eACpB,oBAAoB,sBACpB,oBAAoB,SACtB;AACF;AAEA,SAAS,2BACP,SACsB;CACtB,OAAO,iBAEJ,OAAO,GAAG,CAAC,GAAG,UAA+C;EAC9D,MAAM,sBAAsB,0BAA0B,GAAG,OAAO;EAEhE,EAAE,IAAI,UAAU,oBAAoB,aAAa;EACjD,MAAM,KAAK;EACX,uBAAuB,GAAG,SAAS,mBAAmB;CACxD,CAAC;AACH"}
1
+ {"version":3,"file":"hono_middleware.js","names":[],"sources":["../src/hono_middleware.ts"],"sourcesContent":["import type { MiddlewareHandler } from \"hono\";\nimport { getRuntimeKey } from \"hono/adapter\";\nimport { createMiddleware } from \"hono/factory\";\n\nimport type { LoggerBase } from \"./logger_factory\";\n\nconst DEFAULT_ERROR_STATUS = 500;\nconst DEFAULT_REQUEST_LOGGER_NAME = \"request\";\nconst EMPTY_REQUEST_ID = \"\";\nconst FAILED_REQUEST_MESSAGE = \"Request failed\";\nconst REQUEST_COMPLETED_MESSAGE = \"Request completed\";\nconst REQUEST_ID_HEADER = \"x-request-id\";\nconst EMPTY_QUERY = \"\";\n\ntype RequestRuntimeKey = ReturnType<typeof getRuntimeKey>;\n\ntype HonoLoggerVariables = {\n logger: LoggerBase;\n};\n\ntype HonoLoggerMiddleware = MiddlewareHandler<{\n Variables: HonoLoggerVariables;\n}>;\n\ntype RequestLike = Readonly<{\n header: (name: string) => string | undefined;\n method: string;\n path: string;\n url: string;\n}>;\n\ntype ResponseLike = Readonly<{\n status: number;\n}>;\n\ntype RequestOnlyReader = Readonly<{\n req: RequestLike;\n}>;\n\ntype RequestContextReader = Readonly<{\n error?: unknown;\n req: RequestLike;\n res: ResponseLike;\n}>;\n\ntype MiddlewareContext = Readonly<{\n error?: unknown;\n req: RequestLike;\n res: ResponseLike;\n set: (key: \"logger\", value: Readonly<LoggerBase>) => void;\n}>;\n\ntype MiddlewareParameters = readonly [MiddlewareContext, () => Promise<void>];\n\ntype RequestMetadataValue = number | string;\n\ntype RequestLoggerContext = Readonly<{\n method: string;\n path: string;\n /**\n * The query string including the leading `?` (`\"?a=1&b=2\"`), or `\"\"` when\n * there is none. It is passed to `requestLoggerName` only; the middleware\n * logs it as `query` just when `includeQuery` is on.\n */\n query: string;\n requestId: string;\n runtime: RequestRuntimeKey;\n url: string;\n}>;\n\ntype RequestLoggerNameResolver = (context: RequestLoggerContext) => string;\n\ntype HonoLoggerMiddlewareOptions = Readonly<{\n /**\n * Adds the request's query string (`?a=1&b=2`) to the logged metadata as\n * `query`. Off by default: query strings often carry tokens, OAuth codes and\n * e-mail addresses, and the log keeps only the path.\n */\n includeQuery?: boolean;\n logCompletedRequests?: boolean;\n logger: Readonly<LoggerBase>;\n requestLoggerName?: RequestLoggerNameResolver | string;\n}>;\n\ntype RequestLoggingState = Readonly<{\n requestLogger: Readonly<LoggerBase>;\n requestLoggerContext: RequestLoggerContext;\n startTime: number;\n}>;\n\nfunction resolveRequestId(c: RequestOnlyReader): string {\n const requestId = c.req.header(REQUEST_ID_HEADER);\n\n if (\n typeof requestId !== \"string\" ||\n requestId.length === EMPTY_REQUEST_ID.length\n ) {\n return EMPTY_REQUEST_ID;\n }\n\n return requestId;\n}\n\nfunction extractQuery(url: string): string {\n try {\n return new URL(url).search;\n } catch {\n // Hono hands out absolute URLs; anything else has no query we can trust.\n return EMPTY_QUERY;\n }\n}\n\nfunction createRequestLoggerContext(\n c: RequestOnlyReader,\n): RequestLoggerContext {\n return {\n method: c.req.method,\n path: c.req.path,\n query: extractQuery(c.req.url),\n requestId: resolveRequestId(c),\n runtime: getRuntimeKey(),\n url: c.req.url,\n };\n}\n\nfunction resolveRequestLoggerName(\n requestLoggerContext: RequestLoggerContext,\n requestLoggerName: HonoLoggerMiddlewareOptions[\"requestLoggerName\"],\n): string {\n if (typeof requestLoggerName === \"function\") {\n return requestLoggerName(requestLoggerContext);\n }\n\n if (typeof requestLoggerName === \"string\") {\n return requestLoggerName;\n }\n\n return DEFAULT_REQUEST_LOGGER_NAME;\n}\n\nfunction createRequestLogger(\n logger: Readonly<LoggerBase>,\n requestLoggerContext: RequestLoggerContext,\n requestLoggerName: HonoLoggerMiddlewareOptions[\"requestLoggerName\"],\n): Readonly<LoggerBase> {\n return logger.createChildLogger(\n resolveRequestLoggerName(requestLoggerContext, requestLoggerName),\n );\n}\n\nfunction createRequestOnlyReader(c: MiddlewareContext): RequestOnlyReader {\n return {\n req: {\n header(name: string): string | undefined {\n return c.req.header(name);\n },\n method: c.req.method,\n path: c.req.path,\n url: c.req.url,\n },\n };\n}\n\n/**\n * Reads the response status, so call it only after `next()`. Hono's `c.res`\n * getter creates a placeholder Response on first access, and a handler's own\n * Response is then copied into a new one (`new Response(body, res)`) when it is\n * set. Touching `c.res` before the handler ran therefore replaces every\n * response and loses its identity.\n *\n * @param {MiddlewareContext} c - The Hono context, after `next()` returned.\n * @returns {RequestContextReader} The request, the error and the status.\n */\nfunction createRequestReader(c: MiddlewareContext): RequestContextReader {\n return {\n ...createRequestOnlyReader(c),\n error: c.error,\n res: {\n status: c.res.status,\n },\n };\n}\n\nfunction createRequestLoggingState(\n c: MiddlewareContext,\n options: HonoLoggerMiddlewareOptions,\n): RequestLoggingState {\n const requestLoggerContext = createRequestLoggerContext(\n createRequestOnlyReader(c),\n );\n\n return {\n requestLogger: createRequestLogger(\n options.logger,\n requestLoggerContext,\n options.requestLoggerName,\n ),\n requestLoggerContext,\n startTime: Date.now(),\n };\n}\n\nfunction buildRequestMetadata(\n requestLoggerContext: RequestLoggerContext,\n includeQuery: boolean,\n durationMs: number,\n status: number,\n): Readonly<Record<string, RequestMetadataValue>> {\n const requestMetadata: Record<string, RequestMetadataValue> = {\n durationMs,\n method: requestLoggerContext.method,\n path: requestLoggerContext.path,\n runtime: requestLoggerContext.runtime,\n status,\n };\n\n if (\n includeQuery &&\n requestLoggerContext.query.length > EMPTY_QUERY.length\n ) {\n requestMetadata.query = requestLoggerContext.query;\n }\n\n if (requestLoggerContext.requestId.length > EMPTY_REQUEST_ID.length) {\n requestMetadata.requestId = requestLoggerContext.requestId;\n }\n\n return requestMetadata;\n}\n\nfunction serializeThrownError(\n error: unknown,\n): Readonly<Record<string, string>> {\n if (error instanceof Error) {\n return {\n message: error.message,\n name: error.name,\n stack: error.stack ?? \"\",\n };\n }\n\n return {\n message: String(error),\n name: \"UnknownError\",\n stack: \"\",\n };\n}\n\nfunction getElapsedMilliseconds(startTime: number): number {\n return Date.now() - startTime;\n}\n\nfunction shouldLogCompletedRequests(\n logCompletedRequests: boolean | undefined,\n): boolean {\n return logCompletedRequests ?? true;\n}\n\nfunction shouldIncludeQuery(includeQuery: boolean | undefined): boolean {\n return includeQuery ?? false;\n}\n\nfunction logCompletedRequest(\n c: RequestContextReader,\n requestLogger: Readonly<LoggerBase>,\n requestLoggerContext: RequestLoggerContext,\n includeQuery: boolean,\n startTime: number,\n): void {\n requestLogger.info(\n REQUEST_COMPLETED_MESSAGE,\n buildRequestMetadata(\n requestLoggerContext,\n includeQuery,\n getElapsedMilliseconds(startTime),\n c.res.status,\n ),\n );\n}\n\nfunction logFailedRequest(\n c: RequestContextReader,\n requestLogger: Readonly<LoggerBase>,\n requestLoggerContext: RequestLoggerContext,\n includeQuery: boolean,\n startTime: number,\n): void {\n requestLogger.error(\n FAILED_REQUEST_MESSAGE,\n buildRequestMetadata(\n requestLoggerContext,\n includeQuery,\n getElapsedMilliseconds(startTime),\n c.res.status || DEFAULT_ERROR_STATUS,\n ),\n serializeThrownError(c.error),\n );\n}\n\nfunction finalizeRequestLogging(\n c: MiddlewareContext,\n options: HonoLoggerMiddlewareOptions,\n requestLoggingState: RequestLoggingState,\n): void {\n const requestReader = createRequestReader(c);\n const includeQuery = shouldIncludeQuery(options.includeQuery);\n\n if (typeof requestReader.error !== \"undefined\") {\n logFailedRequest(\n requestReader,\n requestLoggingState.requestLogger,\n requestLoggingState.requestLoggerContext,\n includeQuery,\n requestLoggingState.startTime,\n );\n return;\n }\n\n if (!shouldLogCompletedRequests(options.logCompletedRequests)) {\n return;\n }\n\n logCompletedRequest(\n requestReader,\n requestLoggingState.requestLogger,\n requestLoggingState.requestLoggerContext,\n includeQuery,\n requestLoggingState.startTime,\n );\n}\n\nfunction createHonoLoggerMiddleware(\n options: HonoLoggerMiddlewareOptions,\n): HonoLoggerMiddleware {\n return createMiddleware<{\n Variables: HonoLoggerVariables;\n }>(async (...[c, next]: MiddlewareParameters): Promise<void> => {\n const requestLoggingState = createRequestLoggingState(c, options);\n\n c.set(\"logger\", requestLoggingState.requestLogger);\n await next();\n finalizeRequestLogging(c, options, requestLoggingState);\n });\n}\n\nexport { createHonoLoggerMiddleware };\n\nexport type {\n HonoLoggerMiddlewareOptions,\n HonoLoggerVariables,\n RequestLoggerContext,\n};\n"],"mappings":";;;AAMA,MAAM,uBAAuB;AAC7B,MAAM,8BAA8B;AACpC,MAAM,mBAAmB;AACzB,MAAM,yBAAyB;AAC/B,MAAM,4BAA4B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AAC,2BAA2B,QAAQ,oBAAoB,GACxD;CAGJ,oBACI,eACA,oBAAoB,eACpB,oBAAoB,sBACpB,cACA,oBAAoB,SACxB;AACJ;AAEA,SAAS,2BACL,SACoB;CACpB,OAAO,iBAEJ,OAAO,GAAG,CAAC,GAAG,UAA+C;EAC5D,MAAM,sBAAsB,0BAA0B,GAAG,OAAO;EAEhE,EAAE,IAAI,UAAU,oBAAoB,aAAa;EACjD,MAAM,KAAK;EACX,uBAAuB,GAAG,SAAS,mBAAmB;CAC1D,CAAC;AACL"}
package/dist/logger.d.ts CHANGED
@@ -1,8 +1,6 @@
1
1
  import { LogLevel, LoggerBase, LoggerOptions, LoggerParent } from "./logger_factory.js";
2
- //#region src/logger.d.ts
3
2
  declare class Logger extends LoggerBase {
4
3
  constructor(name: string, parent?: LoggerParent, options?: LoggerOptions);
5
4
  }
6
- //#endregion
7
5
  export { type LogLevel, Logger, type LoggerOptions };
8
6
  //# sourceMappingURL=logger.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"logger.d.ts","names":[],"sources":["../src/logger.ts"],"mappings":";;cAIM,eAAe;EACnB,YACE,cACA,SAAS,cACT,UAAS"}
1
+ {"version":3,"file":"logger.d.ts","names":[],"sources":["../src/logger.ts"],"mappings":";cAIM,eAAe;EACjB,YACI,cACA,SAAS,cACT,UAAS"}
package/dist/logger.js CHANGED
@@ -1,12 +1,11 @@
1
1
  import { LoggerBase } from "./logger_factory.js";
2
2
  import { nodeRuntime } from "./node_runtime.js";
3
- //#region src/logger.ts
3
+ // src/logger.ts
4
4
  var Logger = class Logger extends LoggerBase {
5
5
  constructor(name, parent, options = {}) {
6
6
  super(Logger, nodeRuntime, name, parent, options);
7
7
  }
8
8
  };
9
- //#endregion
10
9
  export { Logger };
11
10
 
12
11
  //# sourceMappingURL=logger.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"logger.js","names":[],"sources":["../src/logger.ts"],"sourcesContent":["import { nodeRuntime } from \"./node_runtime\";\nimport { LoggerBase } from \"./logger_factory\";\nimport type { LoggerOptions, LoggerParent, LogLevel } from \"./logger_factory\";\n\nclass Logger extends LoggerBase {\n constructor(\n name: string,\n parent?: LoggerParent,\n options: LoggerOptions = {},\n ) {\n super(Logger, nodeRuntime, name, parent, options);\n }\n}\n\nexport { Logger };\n\nexport type { LoggerOptions, LogLevel };\n"],"mappings":";;;AAIA,IAAM,SAAN,MAAM,eAAe,WAAW;CAC9B,YACE,MACA,QACA,UAAyB,CAAC,GAC1B;EACA,MAAM,QAAQ,aAAa,MAAM,QAAQ,OAAO;CAClD;AACF"}
1
+ {"version":3,"file":"logger.js","names":[],"sources":["../src/logger.ts"],"sourcesContent":["import { LoggerBase } from \"./logger_factory\";\nimport type { LoggerOptions, LoggerParent, LogLevel } from \"./logger_factory\";\nimport { nodeRuntime } from \"./node_runtime\";\n\nclass Logger extends LoggerBase {\n constructor(\n name: string,\n parent?: LoggerParent,\n options: LoggerOptions = {},\n ) {\n super(Logger, nodeRuntime, name, parent, options);\n }\n}\n\nexport { Logger };\n\nexport type { LoggerOptions, LogLevel };\n"],"mappings":";;;AAIA,IAAM,SAAN,MAAM,eAAe,WAAW;CAC5B,YACI,MACA,QACA,UAAyB,CAAC,GAC5B;EACE,MAAM,QAAQ,aAAa,MAAM,QAAQ,OAAO;CACpD;AACJ"}