@vllnt/logger 0.1.3-canary.bee7353 → 0.2.0-canary.58aea0d
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/CHANGELOG.md +55 -27
- package/README.md +135 -121
- package/dist/{chunk-ZXUJ3U24.js → chunk-XVJGR2V4.js} +82 -14
- package/dist/convex.d.ts +1 -1
- package/dist/convex.js +1 -1
- package/dist/{core-he_ASnDU.d.ts → core-CXZePzIp.d.ts} +23 -8
- package/dist/index.d.ts +8 -3
- package/dist/index.js +1 -1
- package/docs/API.md +36 -12
- package/llms.txt +26 -8
- package/package.json +22 -11
- package/src/backend.ts +6 -1
- package/src/convex.ts +1 -1
- package/src/core.ts +144 -27
- package/src/index.ts +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -4,39 +4,67 @@ All notable changes to this project are documented here. The format follows
|
|
|
4
4
|
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
|
|
5
5
|
[Semantic Versioning](https://semver.org/).
|
|
6
6
|
|
|
7
|
-
## [0.
|
|
7
|
+
## [0.2.0] - 2026-11-28
|
|
8
8
|
|
|
9
9
|
### Added
|
|
10
10
|
|
|
11
|
-
- The npm package ships `docs/API.md` (every public export with
|
|
12
|
-
`CHANGELOG.md` and the TypeScript sources in `src/`, so coding agents can
|
|
13
|
-
the installed version
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
### Fixed
|
|
19
|
-
|
|
20
|
-
- Log calls never throw. A throwing `getLogLevel`, output, or data getter is swallowed instead of
|
|
21
|
-
propagating into the host application; `withTiming` and `withTimingSync` always rethrow the
|
|
22
|
-
original error from the wrapped function.
|
|
23
|
-
- An invalid or throwing `getLogLevel` falls back to `info` instead of silently dropping every entry.
|
|
24
|
-
- `consoleOutput` keeps the entry when data holds a `BigInt` (written as a string), an `Error`
|
|
25
|
-
(written as `{ name, message, stack }`, previously `{}`) or a circular reference
|
|
26
|
-
(written as `"[Circular]"`). Only a throwing `toJSON` or getter still degrades to the minimal line.
|
|
27
|
-
- `consoleOutput` no longer throws when a `console` method throws.
|
|
28
|
-
- `createPostHogOutput` swallows rejected promises returned by `capture` instead of leaving an
|
|
29
|
-
unhandled rejection. `PostHogCapture` now accepts functions returning any value.
|
|
30
|
-
- `withTiming` logs a placeholder when a thrown value cannot be converted to a string.
|
|
11
|
+
- The npm package ships `docs/API.md` (every public export, with a type-checked example for each
|
|
12
|
+
function), `llms.txt`, `CHANGELOG.md` and the TypeScript sources in `src/`, so coding agents can
|
|
13
|
+
read docs that match the installed version in `node_modules/@vllnt/logger/`.
|
|
14
|
+
- README: when to use, an API table of every export, common tasks, errors and fixes, limits and
|
|
15
|
+
gotchas, compatibility and links. Every TypeScript example is type-checked against the built
|
|
16
|
+
package.
|
|
31
17
|
|
|
32
18
|
### Changed
|
|
33
19
|
|
|
34
|
-
- `
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
20
|
+
- `consoleOutput` writes an `Error` in data (also one from another realm such as `node:vm`, or any
|
|
21
|
+
object whose `Object.prototype.toString` tag is `Error`) as its own enumerable fields plus
|
|
22
|
+
`name`, `message` and `stack`; before, it wrote only its own enumerable fields (`{}` for a plain
|
|
23
|
+
`Error`, `{ code, errno, … }` for a Node.js system error). An own field it cannot read is now
|
|
24
|
+
left out instead of giving the `[logger:serialize-error]` line. Stack traces now reach the log
|
|
25
|
+
sink: if it must not store them, map errors to plain data before logging.
|
|
26
|
+
- `consoleOutput` keeps the entry when data holds a `BigInt` (written as a string) or a circular
|
|
27
|
+
reference (written as `"[Circular]"`) instead of writing the `[logger:serialize-error]` line.
|
|
28
|
+
Expect strings for these fields when you read the logs.
|
|
29
|
+
- `consoleOutput` never throws: a throwing `console` method or a throwing `event` or `level`
|
|
30
|
+
getter is swallowed. The `[logger:serialize-error]` line leaves out a field it cannot read, and
|
|
31
|
+
data nested thousands of levels deep still gives that line. No action needed.
|
|
32
|
+
- Log calls never throw: an error from `getLogLevel`, an output or a data getter is swallowed
|
|
33
|
+
instead of reaching the caller. A throwing data getter drops the entry; a throwing output has
|
|
34
|
+
already received it. If you relied on that error, catch it inside your output or check your data
|
|
35
|
+
before logging.
|
|
36
|
+
- `getLogLevel` results go through `parseLogLevel`: a level in another case or with spaces
|
|
37
|
+
(`"WARN"`) now selects that level, and any other value, or a throw, falls back to `info`, instead
|
|
38
|
+
of dropping every entry or throwing. Return a valid `LogLevel` to choose another level.
|
|
39
|
+
- `withTiming` and `withTimingSync` always run `execute` and return its result or rethrow its
|
|
40
|
+
original error. A throwing output or `extraData` getter no longer stops `execute` from running
|
|
41
|
+
(at `.start`) or replaces its result or error (at `.complete` and `.error`); only entries that
|
|
42
|
+
cannot be built are dropped. Keep catching errors around the call as before.
|
|
43
|
+
- The `.error` entry of `withTiming` and `withTimingSync` logs the `message` of an `Error` from
|
|
44
|
+
another realm (or any object tagged `Error`) instead of `String(error)` (`"<name>: <message>"`
|
|
45
|
+
for such an Error, `"[object Error]"` for a plain tagged object); `String(error)` (for example
|
|
46
|
+
`"Error: 42"`) when an Error's `message` is not a string, instead of the raw value; and
|
|
47
|
+
`"[unprintable error]"` when a thrown value cannot be converted to a string, instead of
|
|
48
|
+
replacing the original error with a `TypeError`. Update log queries that matched the old text.
|
|
49
|
+
- `createPostHogOutput` catches a rejection of a promise or other thenable that `capture` returns,
|
|
50
|
+
instead of leaving an unhandled rejection (which stops Node.js by default). It now calls `then`
|
|
51
|
+
on any thenable `capture` returns, so a lazy thenable starts. Watch delivery failures in your
|
|
52
|
+
PostHog client if you need them.
|
|
53
|
+
- `PostHogCapture` returns `unknown` instead of `void`; every function accepted before is still
|
|
54
|
+
accepted. No action needed.
|
|
55
|
+
- `package.json` `exports` lists the `types` condition first, and the package is built with tsup 9
|
|
56
|
+
and TypeScript 6: the subpath `.d.ts` files import shared types from `./index.js`. Apart from
|
|
57
|
+
`PostHogCapture`, the types consumers see do not change. No action needed.
|
|
58
|
+
- `package.json`: new `description`, `homepage`, `keywords`, `funding` and `bugs`; `author` is an
|
|
59
|
+
object.
|
|
60
|
+
- Releases: `@latest` publishes only from a `vX.Y.Z` tag on `main` (pushed, or picked for a manual
|
|
61
|
+
run) instead of a manual run that bumped the version, and a manual run on `main` now publishes a
|
|
62
|
+
canary. `@canary` also publishes when only `docs/`, `README.md`, `CHANGELOG.md`, `llms.txt`,
|
|
63
|
+
`LICENSE` or `package.json` change, and a canary built after a release is numbered above it (for
|
|
64
|
+
example `0.2.1-canary.<sha>` after `0.2.0`). GitHub release notes now come from this file. No
|
|
65
|
+
action needed.
|
|
66
|
+
- Development only: CI and release workflow hardening, more tests and package checks, and
|
|
67
|
+
upgraded development dependencies. Runtime and peer dependencies are still none.
|
|
40
68
|
|
|
41
69
|
## [0.1.2] - 2026-03-10
|
|
42
70
|
|
package/README.md
CHANGED
|
@@ -1,8 +1,21 @@
|
|
|
1
1
|
# @vllnt/logger
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Zero-dependency structured JSON logger for TypeScript with scoped events, log levels, timing, and console, PostHog and test outputs for Node.js and Convex.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
## For coding agents
|
|
6
|
+
|
|
7
|
+
`node_modules/@vllnt/logger/docs/API.md` documents every export with its signature, and the TypeScript
|
|
8
|
+
sources ship in `node_modules/@vllnt/logger/src/`. Both match the installed version.
|
|
9
|
+
|
|
10
|
+
## When to use
|
|
11
|
+
|
|
12
|
+
- Use it when you want one JSON line per event, with a scoped event name (`auth.login`), from TypeScript.
|
|
13
|
+
- Use it when the same logger API must run in Node.js and in Convex queries, mutations and actions.
|
|
14
|
+
- Use it when log entries should go to several outputs, such as the console and PostHog.
|
|
15
|
+
- Use it when tests should assert on log entries instead of console output.
|
|
16
|
+
- Do not use it when you need log transports, files, rotation, redaction or async batching: use [pino](https://github.com/pinojs/pino) or [winston](https://github.com/winstonjs/winston).
|
|
17
|
+
- Do not use it when entries must be stored and queried later: use [`@vllnt/convex-events`](https://oss.vllnt.com/packages/convex-events).
|
|
18
|
+
- Do not use it for product analytics with consent: use [`@vllnt/analytics`](https://oss.vllnt.com/packages/analytics).
|
|
6
19
|
|
|
7
20
|
## Install
|
|
8
21
|
|
|
@@ -10,188 +23,189 @@ Zero runtime dependencies. Tree-shakeable. Works in Node.js, Convex, browser, an
|
|
|
10
23
|
pnpm add @vllnt/logger
|
|
11
24
|
```
|
|
12
25
|
|
|
13
|
-
##
|
|
14
|
-
|
|
15
|
-
The docs are bundled in the package: `node_modules/@vllnt/logger/docs/API.md` (every export,
|
|
16
|
-
its signature and an example), `llms.txt`, `CHANGELOG.md` and the TypeScript sources in
|
|
17
|
-
`node_modules/@vllnt/logger/src/`. They match the installed version. Read them before writing code.
|
|
18
|
-
|
|
19
|
-
## Quick Start
|
|
26
|
+
## Quick start
|
|
20
27
|
|
|
21
28
|
```ts
|
|
22
29
|
import { createBackendLogger } from "@vllnt/logger";
|
|
23
30
|
|
|
24
31
|
const logger = createBackendLogger("auth");
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
// → {"event":"auth.login","level":"info","timestamp":"...","userId":"123"}
|
|
28
|
-
|
|
29
|
-
logger.warn("rate-limited", { ip: "1.2.3.4" });
|
|
32
|
+
logger.warn("login.failed", { userId: "123" });
|
|
33
|
+
// console.warn: {"userId":"123","event":"auth.login.failed","level":"warn","timestamp":"2026-11-27T12:00:00.000Z"}
|
|
30
34
|
```
|
|
31
35
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
## Subpath Exports
|
|
35
|
-
|
|
36
|
-
| Import | Use Case |
|
|
37
|
-
| ----------------------- | ------------------------------------- |
|
|
38
|
-
| `@vllnt/logger` | Core API + Node.js backend preset |
|
|
39
|
-
| `@vllnt/logger/convex` | Convex-safe logger (no `process.env`) |
|
|
40
|
-
| `@vllnt/logger/posthog` | PostHog output adapter |
|
|
41
|
-
| `@vllnt/logger/testing` | In-memory test output for assertions |
|
|
36
|
+
`createBackendLogger` writes `warn` and `error` by default. Set `LOG_LEVEL=info` or `LOG_LEVEL=debug` to see more.
|
|
42
37
|
|
|
43
38
|
## API
|
|
44
39
|
|
|
45
|
-
Full reference: [docs/API.md](docs/API.md).
|
|
40
|
+
Full reference with signatures and examples: [docs/API.md](docs/API.md).
|
|
41
|
+
|
|
42
|
+
| Export | Import from | What it does |
|
|
43
|
+
| --- | --- | --- |
|
|
44
|
+
| [`createBackendLogger`](docs/API.md#createbackendloggerscope-string-extendedlogger) | `@vllnt/logger` | Node.js logger: level from `LOG_LEVEL` (default `warn`), writes with `consoleOutput` |
|
|
45
|
+
| [`createLogger`](docs/API.md#createloggerscope-string-config-loggerconfig-logger) | `@vllnt/logger` | Logger with your own `getLogLevel` and `output` |
|
|
46
|
+
| [`createExtendedLogger`](docs/API.md#createextendedloggerscope-string-config-loggerconfig-extendedlogger) | `@vllnt/logger` | `createLogger` plus `withTiming` and `withTimingSync` |
|
|
47
|
+
| [`consoleOutput`](docs/API.md#consoleoutputentry-logentry-void) | `@vllnt/logger` | Output that writes one JSON line to `console.debug/info/warn/error` |
|
|
48
|
+
| [`composeOutputs`](docs/API.md#composeoutputsoutputs-logoutput-logoutput) | `@vllnt/logger` | Combines outputs; a throwing output does not stop the others |
|
|
49
|
+
| [`formatLogEntry`](docs/API.md#formatlogentrylevel-loglevel-event-string-data-logdata-logentry) | `@vllnt/logger` | Builds a `LogEntry` without a scope prefix |
|
|
50
|
+
| [`parseLogLevel`](docs/API.md#parseloglevelvalue-string--undefined-defaultlevel-loglevel-loglevel) | `@vllnt/logger` | Parses a string to a `LogLevel`, with a default |
|
|
51
|
+
| [`LogLevel`](docs/API.md#types) | `@vllnt/logger` | Type: `"debug" \| "info" \| "warn" \| "error"` |
|
|
52
|
+
| [`LogData`](docs/API.md#types) | `@vllnt/logger` | Type: `Record<string, unknown>` passed to a log call |
|
|
53
|
+
| [`LogEntry`](docs/API.md#types) | `@vllnt/logger` | Type: `{ event, level, timestamp }` plus your data |
|
|
54
|
+
| [`LogOutput`](docs/API.md#types) | `@vllnt/logger` | Type: `(entry: LogEntry) => void` |
|
|
55
|
+
| [`Logger`](docs/API.md#types) | `@vllnt/logger` | Type: `debug`, `info`, `warn`, `error` methods |
|
|
56
|
+
| [`ExtendedLogger`](docs/API.md#types) | `@vllnt/logger` | Type: `Logger` plus `withTiming`, `withTimingSync` |
|
|
57
|
+
| [`LoggerConfig`](docs/API.md#types) | `@vllnt/logger` | Type: `{ getLogLevel, output }` |
|
|
58
|
+
| [`createConvexLogger`](docs/API.md#createconvexloggerscope-string-level-loglevel-extendedlogger) | `@vllnt/logger/convex` | Convex logger with a fixed level (default `info`); no `process.env` |
|
|
59
|
+
| [`createPostHogOutput`](docs/API.md#createposthogoutputcapture-posthogcapture-logoutput) | `@vllnt/logger/posthog` | Output that calls your PostHog `capture` function |
|
|
60
|
+
| [`PostHogCapture`](docs/API.md#posthogcapture) | `@vllnt/logger/posthog` | Type: `(event, properties?) => unknown` |
|
|
61
|
+
| [`createTestOutput`](docs/API.md#createtestoutput-testoutput) | `@vllnt/logger/testing` | Output that stores entries in memory for assertions |
|
|
62
|
+
| [`TestOutput`](docs/API.md#testoutput) | `@vllnt/logger/testing` | Type: `{ entries, output }` |
|
|
63
|
+
|
|
64
|
+
## Common tasks
|
|
65
|
+
|
|
66
|
+
Set the level of `createBackendLogger` at runtime (read on every log call):
|
|
46
67
|
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
Pre-configured for Node.js. Reads `LOG_LEVEL` from `process.env` lazily on each log call.
|
|
50
|
-
|
|
51
|
-
```ts
|
|
52
|
-
const logger = createBackendLogger("payments");
|
|
53
|
-
logger.info("charge", { amount: 99, currency: "usd" });
|
|
68
|
+
```bash
|
|
69
|
+
LOG_LEVEL=debug node app.js
|
|
54
70
|
```
|
|
55
71
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
Core factory. Bring your own level strategy and output.
|
|
72
|
+
Use your own level and output:
|
|
59
73
|
|
|
60
74
|
```ts
|
|
61
|
-
import { createLogger,
|
|
75
|
+
import { consoleOutput, createLogger, parseLogLevel } from "@vllnt/logger";
|
|
62
76
|
|
|
63
77
|
const logger = createLogger("api", {
|
|
64
|
-
getLogLevel: () => "
|
|
78
|
+
getLogLevel: () => parseLogLevel(process.env.API_LOG_LEVEL, "info"),
|
|
65
79
|
output: consoleOutput,
|
|
66
80
|
});
|
|
81
|
+
logger.info("request", { method: "GET", path: "/health" });
|
|
67
82
|
```
|
|
68
83
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
Same as `createLogger` but adds `withTiming` and `withTimingSync` helpers.
|
|
84
|
+
Time an async call. It logs `<scope>.<label>.start`, then `.complete` with `durationMs`, or `.error` and rethrows:
|
|
72
85
|
|
|
73
86
|
```ts
|
|
74
|
-
|
|
75
|
-
return db.query("SELECT ...");
|
|
76
|
-
});
|
|
77
|
-
// Logs: scope.db.query.start → scope.db.query.complete (with durationMs)
|
|
78
|
-
// On error: scope.db.query.error (with durationMs + error message)
|
|
79
|
-
```
|
|
80
|
-
|
|
81
|
-
### `composeOutputs(...outputs): LogOutput`
|
|
82
|
-
|
|
83
|
-
Fan-out to multiple outputs. Each output is error-isolated.
|
|
87
|
+
import { consoleOutput, createExtendedLogger } from "@vllnt/logger";
|
|
84
88
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
const output = composeOutputs(
|
|
90
|
-
consoleOutput,
|
|
91
|
-
createPostHogOutput(posthog.capture.bind(posthog)),
|
|
92
|
-
);
|
|
89
|
+
const logger = createExtendedLogger("db", { getLogLevel: () => "info", output: consoleOutput });
|
|
90
|
+
const rows = await logger.withTiming("query", async () => [{ id: 1 }], { table: "users" });
|
|
91
|
+
logger.info("rows", { count: rows.length });
|
|
93
92
|
```
|
|
94
93
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
Safe for Convex queries, mutations, and actions. No `process.env` access.
|
|
94
|
+
Log from a Convex query, mutation or action:
|
|
98
95
|
|
|
99
96
|
```ts
|
|
100
97
|
import { createConvexLogger } from "@vllnt/logger/convex";
|
|
101
98
|
|
|
102
|
-
const logger = createConvexLogger("
|
|
103
|
-
logger.info("
|
|
99
|
+
const logger = createConvexLogger("orders", "debug");
|
|
100
|
+
logger.info("created", { orderId: "o_1" });
|
|
104
101
|
```
|
|
105
102
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
Wraps a PostHog-compatible `capture` function as a `LogOutput`. Swallows thrown errors and rejected promises.
|
|
103
|
+
Write to the console and to PostHog (posthog-node):
|
|
109
104
|
|
|
110
105
|
```ts
|
|
106
|
+
import { composeOutputs, consoleOutput, createLogger } from "@vllnt/logger";
|
|
111
107
|
import { createPostHogOutput } from "@vllnt/logger/posthog";
|
|
112
|
-
|
|
113
|
-
|
|
108
|
+
import { PostHog } from "posthog-node";
|
|
109
|
+
|
|
110
|
+
const client = new PostHog("phc_project_api_key");
|
|
111
|
+
const logger = createLogger("billing", {
|
|
112
|
+
getLogLevel: () => "info",
|
|
113
|
+
output: composeOutputs(
|
|
114
|
+
consoleOutput,
|
|
115
|
+
createPostHogOutput((event, properties = {}) =>
|
|
116
|
+
client.capture({ distinctId: "server", event, properties }),
|
|
117
|
+
),
|
|
118
|
+
),
|
|
119
|
+
});
|
|
120
|
+
logger.info("invoice.paid", { invoiceId: "in_1" });
|
|
121
|
+
await client.shutdown();
|
|
114
122
|
```
|
|
115
123
|
|
|
116
|
-
|
|
124
|
+
## Errors and fixes
|
|
117
125
|
|
|
118
|
-
|
|
126
|
+
Log calls never throw. These are the error messages and markers you can see, and their fixes:
|
|
119
127
|
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
128
|
+
| Error or message | Cause | Fix |
|
|
129
|
+
| --- | --- | --- |
|
|
130
|
+
| `[logger:serialize-error] event=<event> level=<level>` written instead of JSON | `consoleOutput` could not serialize the entry: a value has a throwing `toJSON`, a nested object has a throwing getter, or the data is nested thousands of levels deep. A field of this line that cannot be read is left out | Log plain, shallow data; convert class instances before logging |
|
|
131
|
+
| `"[Circular]"` as a field value | The data has a circular reference | None needed; log a plain copy to keep the full value |
|
|
132
|
+
| `"error": "[unprintable error]"` in a `<label>.error` entry | `withTiming` caught a value whose conversion to a string throws | Throw `Error` instances |
|
|
133
|
+
| The error from your function, after a `<label>.error` entry | `withTiming` and `withTimingSync` rethrow the original error | Catch it around the `withTiming` call |
|
|
134
|
+
| `ERR_PACKAGE_PATH_NOT_EXPORTED` from `require("@vllnt/logger")` | The package is ESM only and has no `require` export. A CommonJS project built with `moduleResolution: nodenext` type-checks, but its output calls `require` and fails here at runtime | Use `import`; in CommonJS use `await import("@vllnt/logger")`, a `.mts` file, or `"type": "module"` |
|
|
135
|
+
| `TS2307: Cannot find module '@vllnt/logger'` (TypeScript 6 reports `TS5107`, `node10` is deprecated, first) | TypeScript `moduleResolution` is `node10` (`node`), which ignores `exports` | Set `moduleResolution` to `nodenext`, `node16` or `bundler` |
|
|
136
|
+
| `TS1479: The current file is a CommonJS module whose imports will produce 'require' calls` | A CommonJS file under `node16` imports this ESM package | Add `"type": "module"`, use a `.mts` file, or use `await import()` |
|
|
123
137
|
|
|
124
|
-
|
|
125
|
-
const logger = createLogger("test", {
|
|
126
|
-
getLogLevel: () => "debug",
|
|
127
|
-
output,
|
|
128
|
-
});
|
|
138
|
+
## Limits and gotchas
|
|
129
139
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
140
|
+
- `createBackendLogger` defaults to `warn`: `debug` and `info` calls write nothing until `LOG_LEVEL` is set. `withTiming` logs `.start` and `.complete` at `info`, so only `.error` shows at the default.
|
|
141
|
+
- `createConvexLogger` uses its fixed `level` (default `info`) and never reads environment variables.
|
|
142
|
+
- An invalid `LOG_LEVEL` falls back to `warn`. A custom `getLogLevel` that returns an invalid value or throws falls back to `info`.
|
|
143
|
+
- Data keys `event`, `level` and `timestamp` are silently replaced by the logger's values.
|
|
144
|
+
- `formatLogEntry` does not add the scope prefix; only logger methods do.
|
|
145
|
+
- A throwing output is swallowed without a trace. Outputs are synchronous: a returned promise is not awaited. `createPostHogOutput` swallows rejected promises, but a promise rejected by any other output is not handled; in Node.js that is an unhandled rejection, so catch inside an async output.
|
|
146
|
+
- `composeOutputs` calls outputs in order, each with the same entry object, so an output must not mutate the entry. A throwing output does not stop the next one.
|
|
147
|
+
- A throwing getter at the top level of log-call data, or of `withTiming`/`withTimingSync` `extraData`, drops that entry silently: it runs while the entry is built. The timing helpers still return the result or rethrow the original error. A throwing getter deeper down gives the `[logger:serialize-error]` line.
|
|
148
|
+
- `consoleOutput` writes `BigInt` as a string and an `Error`, also one from another realm such as `node:vm`, as its own enumerable fields (such as `code` and `errno`) plus `name`, `message` and `stack`. Like `JSON.stringify`, it writes `Map` and `Set` as `{}` and `NaN` as `null`; it drops `undefined`, functions and symbols from objects and writes them as `null` in arrays.
|
|
149
|
+
- `withTiming` logs `error.message` verbatim, without the stack. There is no redaction.
|
|
150
|
+
- `withTiming` and `withTimingSync` replace `extraData.durationMs` in `.complete` and `.error`, and `extraData.error` in `.error`; `.start` logs `extraData` unchanged.
|
|
151
|
+
- `createTestOutput` keeps every entry in memory; create a new one per test.
|
|
133
152
|
|
|
134
|
-
|
|
153
|
+
## Compatibility
|
|
135
154
|
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
155
|
+
- Runtime dependencies: none. Peer dependencies: none.
|
|
156
|
+
- ESM only, with typings for every entry point. TypeScript `moduleResolution` must be `nodenext`, `node16` or `bundler`, and the importing file must be ESM: in a CommonJS project, `nodenext` type-checks but the emitted `require` fails at runtime.
|
|
157
|
+
- Node.js: no `engines` field. The build targets ES2024; CI tests on Node.js 24.
|
|
158
|
+
- Convex: `@vllnt/logger/convex` does not read `process.env`. Browsers and edge runtimes: the core uses no Node.js APIs and `createBackendLogger` checks for `process` first, but tests run only on Node.js.
|
|
159
|
+
- PostHog: with posthog-js, pass `(event, properties) => posthog.capture(event, properties)` so `capture` keeps its `this`. posthog-node needs the wrapper shown above; it is type-checked against posthog-node 6.
|
|
141
160
|
|
|
142
|
-
##
|
|
161
|
+
## Testing
|
|
162
|
+
|
|
163
|
+
Capture entries with `createTestOutput` and assert on them:
|
|
143
164
|
|
|
144
165
|
```ts
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
debug;
|
|
154
|
-
info;
|
|
155
|
-
warn;
|
|
156
|
-
error: (event: string, data?: LogData) => void;
|
|
157
|
-
};
|
|
158
|
-
type ExtendedLogger = Logger & { withTiming; withTimingSync };
|
|
159
|
-
type LoggerConfig = { getLogLevel: () => LogLevel; output: LogOutput };
|
|
166
|
+
import assert from "node:assert/strict";
|
|
167
|
+
import { createLogger } from "@vllnt/logger";
|
|
168
|
+
import { createTestOutput } from "@vllnt/logger/testing";
|
|
169
|
+
|
|
170
|
+
const { entries, output } = createTestOutput();
|
|
171
|
+
const logger = createLogger("checkout", { getLogLevel: () => "debug", output });
|
|
172
|
+
logger.info("paid", { orderId: "o_1" });
|
|
173
|
+
assert.equal(entries[0]?.event, "checkout.paid");
|
|
160
174
|
```
|
|
161
175
|
|
|
162
|
-
##
|
|
176
|
+
## Security
|
|
163
177
|
|
|
164
|
-
-
|
|
165
|
-
|
|
166
|
-
- **Log calls never throw**: a failing `getLogLevel`, output, or data getter is swallowed; an invalid level falls back to `info`
|
|
167
|
-
- **Crash-safe serialization**: `consoleOutput` writes `BigInt` as a string, `Error` as `{ name, message, stack }`, and circular refs as `"[Circular]"`; a throwing `toJSON` degrades to a minimal `event`/`level` line
|
|
168
|
-
- **No built-in redaction**: pass only data you are willing to log. `withTiming` logs `error.message` verbatim, so sanitize sensitive errors before throwing them
|
|
169
|
-
- **Synchronous outputs**: `LogOutput` is synchronous by design — async adapters manage their own promises
|
|
170
|
-
- **Lazy level evaluation**: `getLogLevel()` is called per-emit, so env changes are picked up without restart
|
|
171
|
-
- **Zero side effects**: Core module has zero module-level side effects (`sideEffects: false`)
|
|
178
|
+
There is no built-in redaction: pass only data you are willing to log. Report vulnerabilities as described in
|
|
179
|
+
[SECURITY.md](https://github.com/vllnt/logger/blob/main/SECURITY.md).
|
|
172
180
|
|
|
173
181
|
## Related packages
|
|
174
182
|
|
|
175
|
-
|
|
176
|
-
management. Use it for user behaviour; use this logger for operational logs.
|
|
177
|
-
- [`@vllnt/convex-events`](https://oss.vllnt.com/packages/convex-events): an append-only activity
|
|
178
|
-
feed stored in Convex. Use it when entries must be stored and queried later; this logger only
|
|
179
|
-
writes to outputs such as the console.
|
|
183
|
+
None. This package has no runtime or peer dependencies, and no other @vllnt package shares code, a test or an example with it.
|
|
180
184
|
|
|
181
|
-
##
|
|
185
|
+
## Contributing
|
|
182
186
|
|
|
183
|
-
|
|
184
|
-
nothing is published from a
|
|
187
|
+
See [CONTRIBUTING.md](https://github.com/vllnt/logger/blob/main/CONTRIBUTING.md). Every publish runs in
|
|
188
|
+
`.github/workflows/publish.yml` with npm trusted publishing and provenance; nothing is published from a
|
|
189
|
+
local machine. Maintainers only.
|
|
185
190
|
|
|
186
191
|
- Canary (`@canary`): every push to `main` that touches the package publishes one
|
|
187
192
|
(`pnpm add @vllnt/logger@canary`).
|
|
188
193
|
- Stable (`@latest`): merge a PR that sets `package.json` `version` and adds a matching
|
|
189
194
|
`## [X.Y.Z]` entry to `CHANGELOG.md`, then push the tag `vX.Y.Z` on that `main` commit.
|
|
190
195
|
|
|
196
|
+
## Links
|
|
197
|
+
|
|
198
|
+
- Docs and changelog: [oss.vllnt.com/packages/logger](https://oss.vllnt.com/packages/logger) · [release feed](https://oss.vllnt.com/packages/logger/rss.xml)
|
|
199
|
+
- All @vllnt packages: [oss.vllnt.com](https://oss.vllnt.com) · [search packages and docs on index.vllnt.com](https://index.vllnt.com)
|
|
200
|
+
- Source and issues: [GitHub](https://github.com/vllnt/logger) · [issues](https://github.com/vllnt/logger/issues) · [npm](https://www.npmjs.com/package/@vllnt/logger)
|
|
201
|
+
- Questions and updates: [Discord](https://bntvllnt.com/discord) · [X @bntvllnt](https://x.com/bntvllnt)
|
|
202
|
+
- Company and author: [vllnt.com](https://vllnt.com) · [bntvllnt.com](https://bntvllnt.com) · [GitHub @bntvllnt](https://github.com/bntvllnt) · [LinkedIn](https://linkedin.com/in/bntvllnt)
|
|
203
|
+
- Sponsor: [GitHub Sponsors](https://github.com/sponsors/bntvllnt)
|
|
204
|
+
|
|
191
205
|
## License
|
|
192
206
|
|
|
193
207
|
[MIT](LICENSE)
|
|
194
208
|
|
|
195
209
|
---
|
|
196
210
|
|
|
197
|
-
Part of vllnt oss
|
|
211
|
+
Part of [vllnt open source](https://oss.vllnt.com) · [Package page](https://oss.vllnt.com/packages/logger) · [vllnt.com](https://vllnt.com) · Built by [bntvllnt](https://bntvllnt.com)
|
|
@@ -54,30 +54,78 @@ function createLogger(scope, config) {
|
|
|
54
54
|
}
|
|
55
55
|
};
|
|
56
56
|
}
|
|
57
|
+
var ERROR_FIELDS = [
|
|
58
|
+
"message",
|
|
59
|
+
"name",
|
|
60
|
+
"stack"
|
|
61
|
+
];
|
|
62
|
+
function ownKeys(value) {
|
|
63
|
+
try {
|
|
64
|
+
return Object.keys(value);
|
|
65
|
+
} catch {
|
|
66
|
+
return [];
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function readEntry(value, key) {
|
|
70
|
+
try {
|
|
71
|
+
const field = Reflect.get(value, key);
|
|
72
|
+
return [[key, field]];
|
|
73
|
+
} catch {
|
|
74
|
+
return [];
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function readError(value) {
|
|
78
|
+
if (typeof value !== "object" || value === null) {
|
|
79
|
+
return void 0;
|
|
80
|
+
}
|
|
81
|
+
try {
|
|
82
|
+
const isError = value instanceof Error || Object.prototype.toString.call(value).slice(8, -1) === "Error";
|
|
83
|
+
if (!isError) {
|
|
84
|
+
return void 0;
|
|
85
|
+
}
|
|
86
|
+
} catch {
|
|
87
|
+
return void 0;
|
|
88
|
+
}
|
|
89
|
+
return Object.fromEntries(
|
|
90
|
+
[...ownKeys(value), ...ERROR_FIELDS].flatMap(
|
|
91
|
+
(key) => readEntry(value, key)
|
|
92
|
+
)
|
|
93
|
+
);
|
|
94
|
+
}
|
|
57
95
|
function formatError(error) {
|
|
96
|
+
const message = readError(error)?.message;
|
|
97
|
+
if (typeof message === "string") {
|
|
98
|
+
return message;
|
|
99
|
+
}
|
|
58
100
|
try {
|
|
59
|
-
return
|
|
101
|
+
return String(error);
|
|
60
102
|
} catch {
|
|
61
103
|
return "[unprintable error]";
|
|
62
104
|
}
|
|
63
105
|
}
|
|
106
|
+
function logBuilt(log, event, build) {
|
|
107
|
+
try {
|
|
108
|
+
log(event, build());
|
|
109
|
+
} catch {
|
|
110
|
+
}
|
|
111
|
+
}
|
|
64
112
|
function createWithTiming(base) {
|
|
65
113
|
return async (label, execute, extraData) => {
|
|
66
114
|
const start = Date.now();
|
|
67
115
|
base.info(`${label}.start`, extraData);
|
|
68
116
|
try {
|
|
69
117
|
const result = await execute();
|
|
70
|
-
base.info
|
|
118
|
+
logBuilt(base.info, `${label}.complete`, () => ({
|
|
71
119
|
...extraData,
|
|
72
120
|
durationMs: Date.now() - start
|
|
73
|
-
});
|
|
121
|
+
}));
|
|
74
122
|
return result;
|
|
75
123
|
} catch (error) {
|
|
76
|
-
base.error
|
|
124
|
+
logBuilt(base.error, `${label}.error`, () => ({
|
|
77
125
|
...extraData,
|
|
78
126
|
durationMs: Date.now() - start,
|
|
79
127
|
error: formatError(error)
|
|
80
|
-
});
|
|
128
|
+
}));
|
|
81
129
|
throw error;
|
|
82
130
|
}
|
|
83
131
|
};
|
|
@@ -88,17 +136,17 @@ function createWithTimingSync(base) {
|
|
|
88
136
|
base.info(`${label}.start`, extraData);
|
|
89
137
|
try {
|
|
90
138
|
const result = execute();
|
|
91
|
-
base.info
|
|
139
|
+
logBuilt(base.info, `${label}.complete`, () => ({
|
|
92
140
|
...extraData,
|
|
93
141
|
durationMs: Date.now() - start
|
|
94
|
-
});
|
|
142
|
+
}));
|
|
95
143
|
return result;
|
|
96
144
|
} catch (error) {
|
|
97
|
-
base.error
|
|
145
|
+
logBuilt(base.error, `${label}.error`, () => ({
|
|
98
146
|
...extraData,
|
|
99
147
|
durationMs: Date.now() - start,
|
|
100
148
|
error: formatError(error)
|
|
101
|
-
});
|
|
149
|
+
}));
|
|
102
150
|
throw error;
|
|
103
151
|
}
|
|
104
152
|
};
|
|
@@ -113,31 +161,51 @@ function createExtendedLogger(scope, config) {
|
|
|
113
161
|
}
|
|
114
162
|
function createReplacer() {
|
|
115
163
|
const ancestors = [];
|
|
164
|
+
const sources = [];
|
|
116
165
|
return function replacer(_key, value) {
|
|
117
166
|
if (typeof value === "bigint") {
|
|
118
167
|
return value.toString();
|
|
119
168
|
}
|
|
120
|
-
const resolved = value
|
|
169
|
+
const resolved = readError(value) ?? value;
|
|
121
170
|
if (typeof resolved !== "object" || resolved === null) {
|
|
122
171
|
return resolved;
|
|
123
172
|
}
|
|
124
|
-
ancestors.
|
|
125
|
-
|
|
173
|
+
const depth = ancestors.indexOf(this) + 1;
|
|
174
|
+
ancestors.splice(depth);
|
|
175
|
+
sources.splice(depth);
|
|
176
|
+
if (sources.includes(value)) {
|
|
126
177
|
return "[Circular]";
|
|
127
178
|
}
|
|
128
179
|
ancestors.push(resolved);
|
|
180
|
+
sources.push(value);
|
|
129
181
|
return resolved;
|
|
130
182
|
};
|
|
131
183
|
}
|
|
184
|
+
function readField(entry, key) {
|
|
185
|
+
try {
|
|
186
|
+
const value = entry[key];
|
|
187
|
+
return String(value);
|
|
188
|
+
} catch {
|
|
189
|
+
return void 0;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
var FALLBACK_FIELDS = ["event", "level"];
|
|
193
|
+
function serializeErrorLine(entry) {
|
|
194
|
+
const fields = FALLBACK_FIELDS.flatMap((key) => {
|
|
195
|
+
const value = readField(entry, key);
|
|
196
|
+
return value === void 0 ? [] : [`${key}=${value}`];
|
|
197
|
+
});
|
|
198
|
+
return ["[logger:serialize-error]", ...fields].join(" ");
|
|
199
|
+
}
|
|
132
200
|
function consoleOutput(entry) {
|
|
133
201
|
let message;
|
|
134
202
|
try {
|
|
135
203
|
message = JSON.stringify(entry, createReplacer());
|
|
136
204
|
} catch {
|
|
137
|
-
message =
|
|
205
|
+
message = serializeErrorLine(entry);
|
|
138
206
|
}
|
|
139
207
|
try {
|
|
140
|
-
switch (entry
|
|
208
|
+
switch (readField(entry, "level") ?? "info") {
|
|
141
209
|
case "debug":
|
|
142
210
|
console.debug(message);
|
|
143
211
|
break;
|
package/dist/convex.d.ts
CHANGED
|
@@ -9,7 +9,7 @@ import { LogLevel, ExtendedLogger } from './index.js';
|
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
11
|
* Create a logger for Convex functions.
|
|
12
|
-
* Pass level explicitly
|
|
12
|
+
* Pass the level explicitly; this logger never reads `process.env`.
|
|
13
13
|
* Defaults to "info".
|
|
14
14
|
*/
|
|
15
15
|
declare function createConvexLogger(scope: string, level?: LogLevel): ExtendedLogger;
|
package/dist/convex.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* Pure functions, ZERO module-level side effects.
|
|
5
5
|
* Safe to import in any runtime (Node, Convex, browser, edge).
|
|
6
6
|
*/
|
|
7
|
-
/**
|
|
7
|
+
/** The four log levels. Severity order: debug < info < warn < error. */
|
|
8
8
|
type LogLevel = "debug" | "error" | "info" | "warn";
|
|
9
9
|
/** Structured log data payload */
|
|
10
10
|
type LogData = Record<string, unknown>;
|
|
@@ -26,11 +26,15 @@ type ExtendedLogger = Logger & {
|
|
|
26
26
|
withTiming: <T>(label: string, execute: () => Promise<T>, extraData?: LogData) => Promise<T>;
|
|
27
27
|
withTimingSync: <T>(label: string, execute: () => T, extraData?: LogData) => T;
|
|
28
28
|
};
|
|
29
|
-
/**
|
|
29
|
+
/**
|
|
30
|
+
* Output handler for log entries. Synchronous by design: the logger does not
|
|
31
|
+
* await or handle a returned promise, so an async output must catch its own
|
|
32
|
+
* rejections.
|
|
33
|
+
*/
|
|
30
34
|
type LogOutput = (entry: LogEntry) => void;
|
|
31
35
|
/** Configuration for creating a logger */
|
|
32
36
|
type LoggerConfig = {
|
|
33
|
-
/** Returns the current log level. Called on every log
|
|
37
|
+
/** Returns the current log level. Called on every log call, including calls its level filters out — keep it cheap. */
|
|
34
38
|
getLogLevel: () => LogLevel;
|
|
35
39
|
output: LogOutput;
|
|
36
40
|
};
|
|
@@ -51,17 +55,28 @@ declare function createLogger(scope: string, config: LoggerConfig): Logger;
|
|
|
51
55
|
/**
|
|
52
56
|
* Create an extended logger with timing helpers.
|
|
53
57
|
*
|
|
54
|
-
* @remarks
|
|
58
|
+
* @remarks The `.error` entry logs the `message` of a caught Error (from any
|
|
59
|
+
* realm) verbatim, and any other value as `String(value)`. An Error whose
|
|
60
|
+
* `message` is not a string logs as `String(error)`, for example `"Error: 42"`.
|
|
55
61
|
* Callers handling sensitive errors should sanitize before throwing.
|
|
62
|
+
* `.complete` and `.error` replace `extraData.durationMs`, and `.error` also
|
|
63
|
+
* replaces `extraData.error`; `.start` logs `extraData` unchanged.
|
|
56
64
|
*/
|
|
57
65
|
declare function createExtendedLogger(scope: string, config: LoggerConfig): ExtendedLogger;
|
|
58
66
|
/**
|
|
59
|
-
* Default console output handler. Never throws
|
|
60
|
-
* circular values; anything still
|
|
61
|
-
*
|
|
67
|
+
* Default console output handler. Never throws, for any `LogEntry`. It handles
|
|
68
|
+
* BigInt, Error (from any realm) and circular values; anything still
|
|
69
|
+
* unserializable (a throwing toJSON or getter, or data nested thousands of
|
|
70
|
+
* levels deep) degrades to a minimal event/level line that leaves out a field
|
|
71
|
+
* it cannot read, and console failures disappear. An unreadable or unknown
|
|
72
|
+
* level writes to `console.info`.
|
|
62
73
|
*/
|
|
63
74
|
declare function consoleOutput(entry: LogEntry): void;
|
|
64
|
-
/**
|
|
75
|
+
/**
|
|
76
|
+
* Compose outputs into a single LogOutput. It calls them in order, each with
|
|
77
|
+
* the same entry object, so an output must not mutate the entry. A throwing
|
|
78
|
+
* output does not stop the next one.
|
|
79
|
+
*/
|
|
65
80
|
declare function composeOutputs(...outputs: LogOutput[]): LogOutput;
|
|
66
81
|
|
|
67
82
|
export { composeOutputs as f, consoleOutput as g, createExtendedLogger as h, createLogger as i, formatLogEntry as j, parseLogLevel as p };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { E as ExtendedLogger } from './core-
|
|
2
|
-
export { a as LogData, b as LogEntry, L as LogLevel, c as LogOutput, d as Logger, e as LoggerConfig, f as composeOutputs, g as consoleOutput, h as createExtendedLogger, i as createLogger, j as formatLogEntry, p as parseLogLevel } from './core-
|
|
1
|
+
import { E as ExtendedLogger } from './core-CXZePzIp.js';
|
|
2
|
+
export { a as LogData, b as LogEntry, L as LogLevel, c as LogOutput, d as Logger, e as LoggerConfig, f as composeOutputs, g as consoleOutput, h as createExtendedLogger, i as createLogger, j as formatLogEntry, p as parseLogLevel } from './core-CXZePzIp.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* @vllnt/logger — Backend preset.
|
|
@@ -8,7 +8,12 @@ export { a as LogData, b as LogEntry, L as LogLevel, c as LogOutput, d as Logger
|
|
|
8
8
|
* Reads LOG_LEVEL from process.env on each call (no module-level side effects).
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
-
/**
|
|
11
|
+
/**
|
|
12
|
+
* Create a scoped Node.js logger that writes with `consoleOutput`. Reads
|
|
13
|
+
* `LOG_LEVEL` from `process.env` on each call; the default is `warn`.
|
|
14
|
+
*
|
|
15
|
+
* @see https://oss.vllnt.com/packages/logger
|
|
16
|
+
*/
|
|
12
17
|
declare function createBackendLogger(scope: string): ExtendedLogger;
|
|
13
18
|
|
|
14
19
|
export { ExtendedLogger, createBackendLogger };
|
package/dist/index.js
CHANGED
package/docs/API.md
CHANGED
|
@@ -18,7 +18,8 @@ its own type declarations.
|
|
|
18
18
|
|
|
19
19
|
Shared types (`LogEntry`, `LogLevel`, …) are exported only from `@vllnt/logger`.
|
|
20
20
|
|
|
21
|
-
Examples use placeholders (`posthog
|
|
21
|
+
Examples use placeholders (`posthog` for a posthog-js instance, `apiKey`, `distinctId`,
|
|
22
|
+
`fetchRows`, `orderId`) and Vitest's `expect`.
|
|
22
23
|
|
|
23
24
|
## Behaviour shared by every logger
|
|
24
25
|
|
|
@@ -31,7 +32,9 @@ Examples use placeholders (`posthog`, `fetchRows`, `orderId`) and Vitest's `expe
|
|
|
31
32
|
- Log calls never throw. A throwing `getLogLevel`, output or data getter is swallowed.
|
|
32
33
|
- Data is spread first, then `event`, `level` and `timestamp` (ISO 8601), so data cannot
|
|
33
34
|
overwrite those three fields.
|
|
34
|
-
- Outputs are synchronous
|
|
35
|
+
- Outputs are synchronous: a returned promise is not awaited. `createPostHogOutput` swallows
|
|
36
|
+
rejections, but a promise rejected by any other output is not handled; in Node.js that is an
|
|
37
|
+
unhandled rejection, so catch inside an async output. There is no built-in redaction.
|
|
35
38
|
|
|
36
39
|
## `@vllnt/logger`
|
|
37
40
|
|
|
@@ -46,7 +49,7 @@ import { createBackendLogger } from "@vllnt/logger";
|
|
|
46
49
|
|
|
47
50
|
const logger = createBackendLogger("payments");
|
|
48
51
|
logger.warn("charge.declined", { amount: 99 });
|
|
49
|
-
// console.warn: {"amount":99,"event":"payments.charge.declined","level":"warn","timestamp":"
|
|
52
|
+
// console.warn: {"amount":99,"event":"payments.charge.declined","level":"warn","timestamp":"2026-11-27T12:00:00.000Z"}
|
|
50
53
|
```
|
|
51
54
|
|
|
52
55
|
### `createLogger(scope: string, config: LoggerConfig): Logger`
|
|
@@ -72,8 +75,13 @@ logger.debug("request", { path: "/health" });
|
|
|
72
75
|
|
|
73
76
|
Both log `info` `<scope>.<label>.start` with `extraData`, then `info` `<scope>.<label>.complete`
|
|
74
77
|
with `extraData` and `durationMs`. If `execute` throws, they log `error` `<scope>.<label>.error`
|
|
75
|
-
with `extraData`, `durationMs` and `error` (the `Error` message
|
|
78
|
+
with `extraData`, `durationMs` and `error` (the `Error` message; `String(error)`, for example
|
|
79
|
+
`"Error: 42"`, when an Error's `message` is not a string; otherwise `String(value)`, or
|
|
76
80
|
`"[unprintable error]"`), then rethrow the original error. The message is logged verbatim.
|
|
81
|
+
An entry whose `extraData` cannot be read (for example a throwing getter) is dropped; the helpers
|
|
82
|
+
still return the result or rethrow the original error. `.complete` and `.error` replace
|
|
83
|
+
`extraData.durationMs`, and `.error` also replaces `extraData.error`; `.start` logs `extraData`
|
|
84
|
+
unchanged. An `Error` from another realm (for example `node:vm`) counts as an `Error`.
|
|
77
85
|
|
|
78
86
|
```ts
|
|
79
87
|
import { consoleOutput, createExtendedLogger } from "@vllnt/logger";
|
|
@@ -89,10 +97,13 @@ const rows = await logger.withTiming("query", () => fetchRows(), { table: "users
|
|
|
89
97
|
### `consoleOutput(entry: LogEntry): void`
|
|
90
98
|
|
|
91
99
|
Default output. Writes `JSON.stringify(entry)` to `console.debug`, `console.info`,
|
|
92
|
-
`console.warn` or `console.error` by level. `BigInt` is written as a string, `Error`
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
100
|
+
`console.warn` or `console.error` by level. `BigInt` is written as a string, an `Error` (also one
|
|
101
|
+
from another realm, such as `node:vm`) as its own enumerable fields (such as `code` and `errno`)
|
|
102
|
+
plus `name`, `message` and `stack`, skipping a field it cannot read, a circular reference as
|
|
103
|
+
`"[Circular]"`. If serialization still fails (a throwing `toJSON` or getter, or data nested
|
|
104
|
+
thousands of levels deep) it writes `[logger:serialize-error] event=<event> level=<level>`,
|
|
105
|
+
leaving out a field it cannot read. An unreadable or unknown `level` writes to `console.info`.
|
|
106
|
+
A throwing `console` method is swallowed. It never throws.
|
|
96
107
|
|
|
97
108
|
```ts
|
|
98
109
|
import { consoleOutput, formatLogEntry } from "@vllnt/logger";
|
|
@@ -102,7 +113,8 @@ consoleOutput(formatLogEntry("error", "job.failed", { error: new Error("timeout"
|
|
|
102
113
|
|
|
103
114
|
### `composeOutputs(...outputs: LogOutput[]): LogOutput`
|
|
104
115
|
|
|
105
|
-
Returns one output that calls each output in order. A throwing output does not stop the
|
|
116
|
+
Returns one output that calls each output in order. A throwing output does not stop the next
|
|
117
|
+
one. Every output receives the same entry object, so an output must not mutate it.
|
|
106
118
|
|
|
107
119
|
```ts
|
|
108
120
|
import { composeOutputs, consoleOutput } from "@vllnt/logger";
|
|
@@ -119,7 +131,7 @@ Builds an entry: `{ ...data, event, level, timestamp }`. It does not add a scope
|
|
|
119
131
|
import { formatLogEntry } from "@vllnt/logger";
|
|
120
132
|
|
|
121
133
|
formatLogEntry("info", "cache.hit", { key: "user:1" });
|
|
122
|
-
// { key: "user:1", event: "cache.hit", level: "info", timestamp: "2026
|
|
134
|
+
// { key: "user:1", event: "cache.hit", level: "info", timestamp: "2026-11-27T12:00:00.000Z" }
|
|
123
135
|
```
|
|
124
136
|
|
|
125
137
|
### `parseLogLevel(value: string | undefined, defaultLevel?: LogLevel): LogLevel`
|
|
@@ -182,8 +194,7 @@ logger.info("created", { orderId });
|
|
|
182
194
|
Calls `capture(entry.event, properties)`, where `properties` is the entry without `event`
|
|
183
195
|
(`level`, `timestamp` and your data). Errors thrown by `capture`, and rejections of a promise it
|
|
184
196
|
returns, are swallowed. No PostHog SDK dependency: pass your own function. posthog-js
|
|
185
|
-
`capture(event, properties)`
|
|
186
|
-
`(event, properties) => client.capture({ distinctId, event, properties })`.
|
|
197
|
+
`capture(event, properties)` takes the same parameters; the arrow wrapper keeps its `this` bound:
|
|
187
198
|
|
|
188
199
|
```ts
|
|
189
200
|
import { createLogger } from "@vllnt/logger";
|
|
@@ -195,6 +206,19 @@ const logger = createLogger("billing", {
|
|
|
195
206
|
});
|
|
196
207
|
```
|
|
197
208
|
|
|
209
|
+
posthog-node `capture` takes one object, so wrap it. The `= {}` default keeps the wrapper valid
|
|
210
|
+
under `exactOptionalPropertyTypes`, where posthog-node's `properties` does not accept `undefined`:
|
|
211
|
+
|
|
212
|
+
```ts
|
|
213
|
+
import { createPostHogOutput } from "@vllnt/logger/posthog";
|
|
214
|
+
import { PostHog } from "posthog-node";
|
|
215
|
+
|
|
216
|
+
const client = new PostHog(apiKey);
|
|
217
|
+
const output = createPostHogOutput((event, properties = {}) =>
|
|
218
|
+
client.capture({ distinctId, event, properties }),
|
|
219
|
+
);
|
|
220
|
+
```
|
|
221
|
+
|
|
198
222
|
### `PostHogCapture`
|
|
199
223
|
|
|
200
224
|
```ts
|
package/llms.txt
CHANGED
|
@@ -1,33 +1,51 @@
|
|
|
1
1
|
# @vllnt/logger
|
|
2
2
|
|
|
3
|
-
>
|
|
3
|
+
> Zero-dependency structured JSON logger for TypeScript with scoped events, log levels, timing, and console, PostHog and test outputs for Node.js and Convex.
|
|
4
4
|
|
|
5
|
-
Scoped events (`auth.login`), levels `debug`, `info`, `warn`, `error`, and pluggable synchronous outputs. The Node.js
|
|
5
|
+
Scoped events (`auth.login`), levels `debug`, `info`, `warn`, `error`, and pluggable synchronous outputs. Log calls never throw. The Node.js preset `createBackendLogger` reads `LOG_LEVEL` from `process.env` on each call and defaults to `warn`. There is no built-in redaction. ESM only; TypeScript `moduleResolution` must be `nodenext`, `node16` or `bundler`.
|
|
6
6
|
|
|
7
7
|
## For coding agents
|
|
8
8
|
|
|
9
9
|
The docs are bundled in the package at `node_modules/@vllnt/logger/docs/`, with the TypeScript sources in `node_modules/@vllnt/logger/src/`. They match the installed version. Read them before writing code.
|
|
10
10
|
|
|
11
|
+
## When to use
|
|
12
|
+
|
|
13
|
+
- Use it when you want one JSON line per event, with a scoped event name, from TypeScript.
|
|
14
|
+
- Use it when the same logger API must run in Node.js and in Convex queries, mutations and actions.
|
|
15
|
+
- Use it when log entries should go to several outputs, such as the console and PostHog.
|
|
16
|
+
- Use it when tests should assert on log entries instead of console output.
|
|
17
|
+
- Do not use it when you need log transports, files, rotation, redaction or async batching: use pino or winston.
|
|
18
|
+
- Do not use it when entries must be stored and queried later: use [`@vllnt/convex-events`](https://oss.vllnt.com/packages/convex-events).
|
|
19
|
+
- Do not use it for product analytics with consent: use [`@vllnt/analytics`](https://oss.vllnt.com/packages/analytics).
|
|
20
|
+
|
|
11
21
|
## Docs
|
|
12
22
|
|
|
13
23
|
- [API Reference](./docs/API.md): Every public export, its signature and an example, per entry point
|
|
14
|
-
- [
|
|
24
|
+
- [Errors and fixes](./README.md#errors-and-fixes): Every error message and marker, its cause and the fix
|
|
25
|
+
- [Limits and gotchas](./README.md#limits-and-gotchas): Defaults and calls that silently do nothing
|
|
26
|
+
- [README](./README.md): Install, quick start, API table, common tasks and compatibility
|
|
15
27
|
- [Changelog](./CHANGELOG.md): Version history and release notes
|
|
28
|
+
- [Links](./README.md#links): Package page, release feed, source, issues, npm and community links
|
|
16
29
|
|
|
17
30
|
## Entry points
|
|
18
31
|
|
|
19
|
-
- `@vllnt/logger`: core API and Node.js
|
|
32
|
+
- `@vllnt/logger`: core API and Node.js preset (`createBackendLogger`)
|
|
20
33
|
- `@vllnt/logger/convex`: `createConvexLogger`, no `process.env` access
|
|
21
34
|
- `@vllnt/logger/posthog`: `createPostHogOutput`
|
|
22
35
|
- `@vllnt/logger/testing`: `createTestOutput`
|
|
23
36
|
|
|
24
|
-
## Ecosystem
|
|
25
|
-
|
|
26
|
-
- [vllnt oss](https://oss.vllnt.com/llms.txt): Index of all @vllnt open-source packages
|
|
27
|
-
|
|
28
37
|
## Optional
|
|
29
38
|
|
|
30
39
|
- [Contributing](https://github.com/vllnt/logger/blob/main/CONTRIBUTING.md): Development setup and release flow
|
|
31
40
|
- [AGENTS](https://github.com/vllnt/logger/blob/main/AGENTS.md): Agent instructions for working on this repository (not shipped in the package)
|
|
32
41
|
- [Security Policy](https://github.com/vllnt/logger/blob/main/SECURITY.md): Vulnerability reporting
|
|
33
42
|
- [License](./LICENSE): MIT
|
|
43
|
+
|
|
44
|
+
## Ecosystem
|
|
45
|
+
|
|
46
|
+
- [Package page](https://oss.vllnt.com/packages/logger)
|
|
47
|
+
- [Release feed](https://oss.vllnt.com/packages/logger/rss.xml)
|
|
48
|
+
- [All @vllnt packages](https://oss.vllnt.com/llms.txt)
|
|
49
|
+
- [Search vllnt packages and docs](https://index.vllnt.com)
|
|
50
|
+
- [vllnt](https://vllnt.com/llms.txt)
|
|
51
|
+
- [Author](https://bntvllnt.com)
|
package/package.json
CHANGED
|
@@ -1,24 +1,37 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vllnt/logger",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0-canary.58aea0d",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"description": "
|
|
5
|
+
"description": "Zero-dependency structured JSON logger for TypeScript with scoped events, log levels, timing, and console, PostHog and test outputs for Node.js and Convex.",
|
|
6
6
|
"license": "MIT",
|
|
7
|
-
"author":
|
|
7
|
+
"author": {
|
|
8
|
+
"name": "bntvllnt",
|
|
9
|
+
"url": "https://bntvllnt.com"
|
|
10
|
+
},
|
|
11
|
+
"funding": {
|
|
12
|
+
"type": "github",
|
|
13
|
+
"url": "https://github.com/sponsors/bntvllnt"
|
|
14
|
+
},
|
|
8
15
|
"homepage": "https://oss.vllnt.com/packages/logger",
|
|
9
16
|
"repository": {
|
|
10
17
|
"type": "git",
|
|
11
18
|
"url": "https://github.com/vllnt/logger"
|
|
12
19
|
},
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/vllnt/logger/issues"
|
|
22
|
+
},
|
|
13
23
|
"keywords": [
|
|
14
24
|
"logger",
|
|
15
25
|
"logging",
|
|
16
26
|
"structured-logging",
|
|
17
|
-
"json",
|
|
27
|
+
"json-logger",
|
|
28
|
+
"log-levels",
|
|
29
|
+
"typescript",
|
|
30
|
+
"nodejs",
|
|
18
31
|
"convex",
|
|
19
32
|
"posthog",
|
|
20
|
-
"
|
|
21
|
-
"
|
|
33
|
+
"zero-dependency",
|
|
34
|
+
"esm"
|
|
22
35
|
],
|
|
23
36
|
"sideEffects": false,
|
|
24
37
|
"exports": {
|
|
@@ -48,11 +61,12 @@
|
|
|
48
61
|
],
|
|
49
62
|
"scripts": {
|
|
50
63
|
"build": "tsup",
|
|
51
|
-
"check-types": "tsc --noEmit --incremental --tsBuildInfoFile node_modules/.cache/tsc/check-types.tsbuildinfo",
|
|
64
|
+
"check-types": "tsc --noEmit -p tsconfig.check.json --incremental --tsBuildInfoFile node_modules/.cache/tsc/check-types.tsbuildinfo",
|
|
52
65
|
"lint": "eslint --cache --cache-location node_modules/.cache/eslint/ --max-warnings 0",
|
|
53
66
|
"lint:fix": "eslint --cache --cache-location node_modules/.cache/eslint/ --fix",
|
|
54
67
|
"test": "vitest run",
|
|
55
68
|
"test:coverage": "vitest run --coverage --coverage.include=src --coverage.reporter=text",
|
|
69
|
+
"test:package": "bash scripts/test-package.sh",
|
|
56
70
|
"test:watch": "vitest"
|
|
57
71
|
},
|
|
58
72
|
"publishConfig": {
|
|
@@ -65,6 +79,7 @@
|
|
|
65
79
|
"@vllnt/eslint-config": "^2.1.0",
|
|
66
80
|
"@vllnt/typescript": "^3.0.0",
|
|
67
81
|
"eslint": "^9.39.5",
|
|
82
|
+
"posthog-node": "^6.0.5",
|
|
68
83
|
"prettier": "^3.10.1",
|
|
69
84
|
"tsup": "^9.0.0",
|
|
70
85
|
"typescript": "^6.0.3",
|
|
@@ -72,10 +87,6 @@
|
|
|
72
87
|
},
|
|
73
88
|
"packageManager": "pnpm@10.34.8",
|
|
74
89
|
"pnpm": {
|
|
75
|
-
"minimumReleaseAge": 10080,
|
|
76
|
-
"minimumReleaseAgeExclude": [
|
|
77
|
-
"@vllnt/*"
|
|
78
|
-
],
|
|
79
90
|
"ignoredBuiltDependencies": [
|
|
80
91
|
"esbuild"
|
|
81
92
|
],
|
package/src/backend.ts
CHANGED
|
@@ -26,7 +26,12 @@ function getBackendLogLevel(): LogLevel {
|
|
|
26
26
|
return parseLogLevel(getEnvironmentVariable("LOG_LEVEL"), "warn");
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
-
/**
|
|
29
|
+
/**
|
|
30
|
+
* Create a scoped Node.js logger that writes with `consoleOutput`. Reads
|
|
31
|
+
* `LOG_LEVEL` from `process.env` on each call; the default is `warn`.
|
|
32
|
+
*
|
|
33
|
+
* @see https://oss.vllnt.com/packages/logger
|
|
34
|
+
*/
|
|
30
35
|
export function createBackendLogger(scope: string): ExtendedLogger {
|
|
31
36
|
return createExtendedLogger(scope, {
|
|
32
37
|
getLogLevel: getBackendLogLevel,
|
package/src/convex.ts
CHANGED
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
|
|
15
15
|
/**
|
|
16
16
|
* Create a logger for Convex functions.
|
|
17
|
-
* Pass level explicitly
|
|
17
|
+
* Pass the level explicitly; this logger never reads `process.env`.
|
|
18
18
|
* Defaults to "info".
|
|
19
19
|
*/
|
|
20
20
|
export function createConvexLogger(
|
package/src/core.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* Safe to import in any runtime (Node, Convex, browser, edge).
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
/**
|
|
8
|
+
/** The four log levels. Severity order: debug < info < warn < error. */
|
|
9
9
|
export type LogLevel = "debug" | "error" | "info" | "warn";
|
|
10
10
|
|
|
11
11
|
/** Structured log data payload */
|
|
@@ -40,12 +40,16 @@ export type ExtendedLogger = Logger & {
|
|
|
40
40
|
) => T;
|
|
41
41
|
};
|
|
42
42
|
|
|
43
|
-
/**
|
|
43
|
+
/**
|
|
44
|
+
* Output handler for log entries. Synchronous by design: the logger does not
|
|
45
|
+
* await or handle a returned promise, so an async output must catch its own
|
|
46
|
+
* rejections.
|
|
47
|
+
*/
|
|
44
48
|
export type LogOutput = (entry: LogEntry) => void;
|
|
45
49
|
|
|
46
50
|
/** Configuration for creating a logger */
|
|
47
51
|
export type LoggerConfig = {
|
|
48
|
-
/** Returns the current log level. Called on every log
|
|
52
|
+
/** Returns the current log level. Called on every log call, including calls its level filters out — keep it cheap. */
|
|
49
53
|
getLogLevel: () => LogLevel;
|
|
50
54
|
output: LogOutput;
|
|
51
55
|
};
|
|
@@ -137,14 +141,88 @@ export function createLogger(scope: string, config: LoggerConfig): Logger {
|
|
|
137
141
|
};
|
|
138
142
|
}
|
|
139
143
|
|
|
144
|
+
const ERROR_FIELDS: readonly ("message" | "name" | "stack")[] = [
|
|
145
|
+
"message",
|
|
146
|
+
"name",
|
|
147
|
+
"stack",
|
|
148
|
+
];
|
|
149
|
+
|
|
150
|
+
/** Return the own enumerable keys of `value`, or none when listing them throws. */
|
|
151
|
+
function ownKeys(value: object): string[] {
|
|
152
|
+
try {
|
|
153
|
+
return Object.keys(value);
|
|
154
|
+
} catch {
|
|
155
|
+
return [];
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Return the key and its value as one entry, or no entry when reading it throws. */
|
|
160
|
+
function readEntry(value: object, key: string): [string, unknown][] {
|
|
161
|
+
try {
|
|
162
|
+
const field: unknown = Reflect.get(value, key);
|
|
163
|
+
return [[key, field]];
|
|
164
|
+
} catch {
|
|
165
|
+
return [];
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Read an Error, including one from another realm (for example `node:vm`),
|
|
171
|
+
* detected by `instanceof` or the `Object.prototype.toString` tag; otherwise
|
|
172
|
+
* return undefined. Avoids `Error.isError` so it runs in Convex and browsers.
|
|
173
|
+
* The result holds the own enumerable fields (such as `code` and `errno`) plus
|
|
174
|
+
* `name`, `message` and `stack`.
|
|
175
|
+
* Never throws: it skips a field it cannot read.
|
|
176
|
+
*/
|
|
177
|
+
function readError(value: unknown): Record<string, unknown> | undefined {
|
|
178
|
+
if (typeof value !== "object" || value === null) {
|
|
179
|
+
return undefined;
|
|
180
|
+
}
|
|
181
|
+
try {
|
|
182
|
+
const isError =
|
|
183
|
+
value instanceof Error ||
|
|
184
|
+
Object.prototype.toString.call(value).slice(8, -1) === "Error";
|
|
185
|
+
if (!isError) {
|
|
186
|
+
return undefined;
|
|
187
|
+
}
|
|
188
|
+
} catch {
|
|
189
|
+
return undefined;
|
|
190
|
+
}
|
|
191
|
+
return Object.fromEntries(
|
|
192
|
+
[...ownKeys(value), ...ERROR_FIELDS].flatMap((key) =>
|
|
193
|
+
readEntry(value, key),
|
|
194
|
+
),
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
|
|
140
198
|
function formatError(error: unknown): string {
|
|
199
|
+
const message = readError(error)?.message;
|
|
200
|
+
if (typeof message === "string") {
|
|
201
|
+
return message;
|
|
202
|
+
}
|
|
141
203
|
try {
|
|
142
|
-
return
|
|
204
|
+
return String(error);
|
|
143
205
|
} catch {
|
|
144
206
|
return "[unprintable error]";
|
|
145
207
|
}
|
|
146
208
|
}
|
|
147
209
|
|
|
210
|
+
/**
|
|
211
|
+
* Build the data and log it. If building throws (for example a throwing
|
|
212
|
+
* getter in `extraData`), drop the entry, as `createLogger` does.
|
|
213
|
+
*/
|
|
214
|
+
function logBuilt(
|
|
215
|
+
log: Logger["info"],
|
|
216
|
+
event: string,
|
|
217
|
+
build: () => LogData,
|
|
218
|
+
): void {
|
|
219
|
+
try {
|
|
220
|
+
log(event, build());
|
|
221
|
+
} catch {
|
|
222
|
+
// Dropped — building the data must not break the timed call
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
148
226
|
function createWithTiming(base: Logger): ExtendedLogger["withTiming"] {
|
|
149
227
|
return async <T>(
|
|
150
228
|
label: string,
|
|
@@ -155,17 +233,17 @@ function createWithTiming(base: Logger): ExtendedLogger["withTiming"] {
|
|
|
155
233
|
base.info(`${label}.start`, extraData);
|
|
156
234
|
try {
|
|
157
235
|
const result = await execute();
|
|
158
|
-
base.info
|
|
236
|
+
logBuilt(base.info, `${label}.complete`, () => ({
|
|
159
237
|
...extraData,
|
|
160
238
|
durationMs: Date.now() - start,
|
|
161
|
-
});
|
|
239
|
+
}));
|
|
162
240
|
return result;
|
|
163
241
|
} catch (error) {
|
|
164
|
-
base.error
|
|
242
|
+
logBuilt(base.error, `${label}.error`, () => ({
|
|
165
243
|
...extraData,
|
|
166
244
|
durationMs: Date.now() - start,
|
|
167
245
|
error: formatError(error),
|
|
168
|
-
});
|
|
246
|
+
}));
|
|
169
247
|
throw error;
|
|
170
248
|
}
|
|
171
249
|
};
|
|
@@ -177,17 +255,17 @@ function createWithTimingSync(base: Logger): ExtendedLogger["withTimingSync"] {
|
|
|
177
255
|
base.info(`${label}.start`, extraData);
|
|
178
256
|
try {
|
|
179
257
|
const result = execute();
|
|
180
|
-
base.info
|
|
258
|
+
logBuilt(base.info, `${label}.complete`, () => ({
|
|
181
259
|
...extraData,
|
|
182
260
|
durationMs: Date.now() - start,
|
|
183
|
-
});
|
|
261
|
+
}));
|
|
184
262
|
return result;
|
|
185
263
|
} catch (error) {
|
|
186
|
-
base.error
|
|
264
|
+
logBuilt(base.error, `${label}.error`, () => ({
|
|
187
265
|
...extraData,
|
|
188
266
|
durationMs: Date.now() - start,
|
|
189
267
|
error: formatError(error),
|
|
190
|
-
});
|
|
268
|
+
}));
|
|
191
269
|
throw error;
|
|
192
270
|
}
|
|
193
271
|
};
|
|
@@ -196,8 +274,12 @@ function createWithTimingSync(base: Logger): ExtendedLogger["withTimingSync"] {
|
|
|
196
274
|
/**
|
|
197
275
|
* Create an extended logger with timing helpers.
|
|
198
276
|
*
|
|
199
|
-
* @remarks
|
|
277
|
+
* @remarks The `.error` entry logs the `message` of a caught Error (from any
|
|
278
|
+
* realm) verbatim, and any other value as `String(value)`. An Error whose
|
|
279
|
+
* `message` is not a string logs as `String(error)`, for example `"Error: 42"`.
|
|
200
280
|
* Callers handling sensitive errors should sanitize before throwing.
|
|
281
|
+
* `.complete` and `.error` replace `extraData.durationMs`, and `.error` also
|
|
282
|
+
* replaces `extraData.error`; `.start` logs `extraData` unchanged.
|
|
201
283
|
*/
|
|
202
284
|
export function createExtendedLogger(
|
|
203
285
|
scope: string,
|
|
@@ -213,8 +295,11 @@ export function createExtendedLogger(
|
|
|
213
295
|
|
|
214
296
|
/**
|
|
215
297
|
* JSON.stringify replacer that keeps entries serializable. It turns BigInt
|
|
216
|
-
* into a string, Error
|
|
217
|
-
* references into "[Circular]".
|
|
298
|
+
* into a string, an Error of any realm into its own enumerable fields plus
|
|
299
|
+
* `name`, `message` and `stack`, and circular references into "[Circular]".
|
|
300
|
+
* Repeated non-circular references stay intact. Tracking the original values
|
|
301
|
+
* on the current path also marks an Error whose own field points back to that
|
|
302
|
+
* Error.
|
|
218
303
|
*/
|
|
219
304
|
function createReplacer(): (
|
|
220
305
|
this: unknown,
|
|
@@ -222,42 +307,70 @@ function createReplacer(): (
|
|
|
222
307
|
value: unknown,
|
|
223
308
|
) => unknown {
|
|
224
309
|
const ancestors: unknown[] = [];
|
|
310
|
+
const sources: unknown[] = [];
|
|
225
311
|
return function replacer(this: unknown, _key: string, value: unknown) {
|
|
226
312
|
if (typeof value === "bigint") {
|
|
227
313
|
return value.toString();
|
|
228
314
|
}
|
|
229
|
-
const resolved =
|
|
230
|
-
value instanceof Error
|
|
231
|
-
? { message: value.message, name: value.name, stack: value.stack }
|
|
232
|
-
: value;
|
|
315
|
+
const resolved = readError(value) ?? value;
|
|
233
316
|
if (typeof resolved !== "object" || resolved === null) {
|
|
234
317
|
return resolved;
|
|
235
318
|
}
|
|
236
319
|
// Drop everything below the current holder: the rest is a finished sibling branch.
|
|
237
|
-
ancestors.
|
|
238
|
-
|
|
320
|
+
const depth = ancestors.indexOf(this) + 1;
|
|
321
|
+
ancestors.splice(depth);
|
|
322
|
+
sources.splice(depth);
|
|
323
|
+
if (sources.includes(value)) {
|
|
239
324
|
return "[Circular]";
|
|
240
325
|
}
|
|
241
326
|
ancestors.push(resolved);
|
|
327
|
+
sources.push(value);
|
|
242
328
|
return resolved;
|
|
243
329
|
};
|
|
244
330
|
}
|
|
245
331
|
|
|
332
|
+
/** Return `String(entry[key])`, or undefined when reading or converting it throws. */
|
|
333
|
+
function readField(
|
|
334
|
+
entry: LogEntry,
|
|
335
|
+
key: "event" | "level",
|
|
336
|
+
): string | undefined {
|
|
337
|
+
try {
|
|
338
|
+
const value: unknown = entry[key];
|
|
339
|
+
return String(value);
|
|
340
|
+
} catch {
|
|
341
|
+
return undefined;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
const FALLBACK_FIELDS: readonly ("event" | "level")[] = ["event", "level"];
|
|
346
|
+
|
|
347
|
+
/** Build the fallback line, leaving out each field it cannot read. */
|
|
348
|
+
function serializeErrorLine(entry: LogEntry): string {
|
|
349
|
+
const fields = FALLBACK_FIELDS.flatMap((key) => {
|
|
350
|
+
const value = readField(entry, key);
|
|
351
|
+
return value === undefined ? [] : [`${key}=${value}`];
|
|
352
|
+
});
|
|
353
|
+
return ["[logger:serialize-error]", ...fields].join(" ");
|
|
354
|
+
}
|
|
355
|
+
|
|
246
356
|
/**
|
|
247
|
-
* Default console output handler. Never throws
|
|
248
|
-
* circular values; anything still
|
|
249
|
-
*
|
|
357
|
+
* Default console output handler. Never throws, for any `LogEntry`. It handles
|
|
358
|
+
* BigInt, Error (from any realm) and circular values; anything still
|
|
359
|
+
* unserializable (a throwing toJSON or getter, or data nested thousands of
|
|
360
|
+
* levels deep) degrades to a minimal event/level line that leaves out a field
|
|
361
|
+
* it cannot read, and console failures disappear. An unreadable or unknown
|
|
362
|
+
* level writes to `console.info`.
|
|
250
363
|
*/
|
|
251
364
|
export function consoleOutput(entry: LogEntry): void {
|
|
252
365
|
let message: string;
|
|
253
366
|
try {
|
|
254
367
|
message = JSON.stringify(entry, createReplacer());
|
|
255
368
|
} catch {
|
|
256
|
-
message =
|
|
369
|
+
message = serializeErrorLine(entry);
|
|
257
370
|
}
|
|
258
371
|
|
|
259
372
|
try {
|
|
260
|
-
switch (entry
|
|
373
|
+
switch (readField(entry, "level") ?? "info") {
|
|
261
374
|
case "debug":
|
|
262
375
|
console.debug(message);
|
|
263
376
|
break;
|
|
@@ -279,7 +392,11 @@ export function consoleOutput(entry: LogEntry): void {
|
|
|
279
392
|
}
|
|
280
393
|
}
|
|
281
394
|
|
|
282
|
-
/**
|
|
395
|
+
/**
|
|
396
|
+
* Compose outputs into a single LogOutput. It calls them in order, each with
|
|
397
|
+
* the same entry object, so an output must not mutate the entry. A throwing
|
|
398
|
+
* output does not stop the next one.
|
|
399
|
+
*/
|
|
283
400
|
export function composeOutputs(...outputs: LogOutput[]): LogOutput {
|
|
284
401
|
return (entry: LogEntry): void => {
|
|
285
402
|
outputs.forEach((output) => {
|
package/src/index.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vllnt/logger —
|
|
2
|
+
* @vllnt/logger — zero-dependency structured JSON logger for TypeScript.
|
|
3
3
|
*
|
|
4
|
-
* Core exports +
|
|
4
|
+
* Core exports + Node.js preset (`createBackendLogger`).
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
7
|
export { createBackendLogger } from "./backend.js";
|