@vllnt/logger 0.1.3-canary.f176c73 → 0.2.0-canary.3574879
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 +87 -0
- package/README.md +142 -108
- 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 +251 -0
- package/llms.txt +51 -0
- package/package.json +43 -14
- package/src/backend.ts +40 -0
- package/src/convex.ts +28 -0
- package/src/core.ts +410 -0
- package/src/index.ts +22 -0
- package/src/posthog.ts +43 -0
- package/src/testing.ts +22 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented here. The format follows
|
|
4
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
|
|
5
|
+
[Semantic Versioning](https://semver.org/).
|
|
6
|
+
|
|
7
|
+
## [0.2.0] - 2026-11-28
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
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.
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
|
|
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. Every push to `main` publishes a canary, whatever files it changes, and a canary built
|
|
63
|
+
after a release is numbered above it (for example `0.2.1-canary.<sha>` after `0.2.0`). GitHub
|
|
64
|
+
release notes now come from this file. No action needed.
|
|
65
|
+
- Development only: CI and release workflow hardening (pnpm through Corepack), more tests and
|
|
66
|
+
package checks, and upgraded development dependencies. Runtime and peer dependencies are still
|
|
67
|
+
none.
|
|
68
|
+
|
|
69
|
+
## [0.1.2] - 2026-03-10
|
|
70
|
+
|
|
71
|
+
### Changed
|
|
72
|
+
|
|
73
|
+
- Publish workflow and CI refinements.
|
|
74
|
+
|
|
75
|
+
## [0.1.1] - 2026-03-10
|
|
76
|
+
|
|
77
|
+
### Changed
|
|
78
|
+
|
|
79
|
+
- Added the publish workflow (trusted publishing, canary and release jobs) and refined CI.
|
|
80
|
+
|
|
81
|
+
## [0.1.0] - 2026-03-09
|
|
82
|
+
|
|
83
|
+
### Added
|
|
84
|
+
|
|
85
|
+
- Initial release: core logger (`createLogger`, `createExtendedLogger`, `composeOutputs`,
|
|
86
|
+
`consoleOutput`, `formatLogEntry`, `parseLogLevel`), Node.js backend preset, and the `/convex`,
|
|
87
|
+
`/posthog` and `/testing` entry points.
|
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,168 +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
|
-
## Quick
|
|
26
|
+
## Quick start
|
|
14
27
|
|
|
15
28
|
```ts
|
|
16
29
|
import { createBackendLogger } from "@vllnt/logger";
|
|
17
30
|
|
|
18
31
|
const logger = createBackendLogger("auth");
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
// → {"event":"auth.login","level":"info","timestamp":"...","userId":"123"}
|
|
22
|
-
|
|
23
|
-
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"}
|
|
24
34
|
```
|
|
25
35
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
## Subpath Exports
|
|
29
|
-
|
|
30
|
-
| Import | Use Case |
|
|
31
|
-
| ----------------------- | ------------------------------------- |
|
|
32
|
-
| `@vllnt/logger` | Core API + Node.js backend preset |
|
|
33
|
-
| `@vllnt/logger/convex` | Convex-safe logger (no `process.env`) |
|
|
34
|
-
| `@vllnt/logger/posthog` | PostHog output adapter |
|
|
35
|
-
| `@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.
|
|
36
37
|
|
|
37
38
|
## API
|
|
38
39
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
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):
|
|
42
67
|
|
|
43
|
-
```
|
|
44
|
-
|
|
45
|
-
logger.info("charge", { amount: 99, currency: "usd" });
|
|
68
|
+
```bash
|
|
69
|
+
LOG_LEVEL=debug node app.js
|
|
46
70
|
```
|
|
47
71
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
Core factory. Bring your own level strategy and output.
|
|
72
|
+
Use your own level and output:
|
|
51
73
|
|
|
52
74
|
```ts
|
|
53
|
-
import { createLogger,
|
|
75
|
+
import { consoleOutput, createLogger, parseLogLevel } from "@vllnt/logger";
|
|
54
76
|
|
|
55
77
|
const logger = createLogger("api", {
|
|
56
|
-
getLogLevel: () => "
|
|
78
|
+
getLogLevel: () => parseLogLevel(process.env.API_LOG_LEVEL, "info"),
|
|
57
79
|
output: consoleOutput,
|
|
58
80
|
});
|
|
81
|
+
logger.info("request", { method: "GET", path: "/health" });
|
|
59
82
|
```
|
|
60
83
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
Same as `createLogger` but adds `withTiming` and `withTimingSync` helpers.
|
|
64
|
-
|
|
65
|
-
```ts
|
|
66
|
-
const result = await logger.withTiming("db.query", async () => {
|
|
67
|
-
return db.query("SELECT ...");
|
|
68
|
-
});
|
|
69
|
-
// Logs: scope.db.query.start → scope.db.query.complete (with durationMs)
|
|
70
|
-
// On error: scope.db.query.error (with durationMs + error message)
|
|
71
|
-
```
|
|
72
|
-
|
|
73
|
-
### `composeOutputs(...outputs): LogOutput`
|
|
74
|
-
|
|
75
|
-
Fan-out to multiple outputs. Each output is error-isolated.
|
|
84
|
+
Time an async call. It logs `<scope>.<label>.start`, then `.complete` with `durationMs`, or `.error` and rethrows:
|
|
76
85
|
|
|
77
86
|
```ts
|
|
78
|
-
import {
|
|
79
|
-
import { createPostHogOutput } from "@vllnt/logger/posthog";
|
|
87
|
+
import { consoleOutput, createExtendedLogger } from "@vllnt/logger";
|
|
80
88
|
|
|
81
|
-
const
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
);
|
|
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 });
|
|
85
92
|
```
|
|
86
93
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
Safe for Convex queries, mutations, and actions. No `process.env` access.
|
|
94
|
+
Log from a Convex query, mutation or action:
|
|
90
95
|
|
|
91
96
|
```ts
|
|
92
97
|
import { createConvexLogger } from "@vllnt/logger/convex";
|
|
93
98
|
|
|
94
|
-
const logger = createConvexLogger("
|
|
95
|
-
logger.info("
|
|
99
|
+
const logger = createConvexLogger("orders", "debug");
|
|
100
|
+
logger.info("created", { orderId: "o_1" });
|
|
96
101
|
```
|
|
97
102
|
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
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):
|
|
101
104
|
|
|
102
105
|
```ts
|
|
106
|
+
import { composeOutputs, consoleOutput, createLogger } from "@vllnt/logger";
|
|
103
107
|
import { createPostHogOutput } from "@vllnt/logger/posthog";
|
|
104
|
-
|
|
105
|
-
|
|
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();
|
|
106
122
|
```
|
|
107
123
|
|
|
108
|
-
|
|
124
|
+
## Errors and fixes
|
|
109
125
|
|
|
110
|
-
|
|
126
|
+
Log calls never throw. These are the error messages and markers you can see, and their fixes:
|
|
111
127
|
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
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()` |
|
|
115
137
|
|
|
116
|
-
|
|
117
|
-
const logger = createLogger("test", {
|
|
118
|
-
getLogLevel: () => "debug",
|
|
119
|
-
output,
|
|
120
|
-
});
|
|
138
|
+
## Limits and gotchas
|
|
121
139
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
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.
|
|
152
|
+
|
|
153
|
+
## Compatibility
|
|
125
154
|
|
|
126
|
-
|
|
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.
|
|
127
160
|
|
|
128
|
-
|
|
129
|
-
| ------------------------------------- | ---------------------------------------------------- |
|
|
130
|
-
| `formatLogEntry(level, event, data?)` | Build a `LogEntry` manually |
|
|
131
|
-
| `parseLogLevel(value, default?)` | Safe `string` to `LogLevel` parsing |
|
|
132
|
-
| `consoleOutput(entry)` | JSON to `console.debug/info/warn/error` (crash-safe) |
|
|
161
|
+
## Testing
|
|
133
162
|
|
|
134
|
-
|
|
163
|
+
Capture entries with `createTestOutput` and assert on them:
|
|
135
164
|
|
|
136
165
|
```ts
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
debug;
|
|
146
|
-
info;
|
|
147
|
-
warn;
|
|
148
|
-
error: (event: string, data?: LogData) => void;
|
|
149
|
-
};
|
|
150
|
-
type ExtendedLogger = Logger & { withTiming; withTimingSync };
|
|
151
|
-
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");
|
|
152
174
|
```
|
|
153
175
|
|
|
154
|
-
##
|
|
176
|
+
## Security
|
|
177
|
+
|
|
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).
|
|
155
180
|
|
|
156
|
-
|
|
157
|
-
- **Reserved field protection**: User data cannot overwrite `event`, `level`, or `timestamp`
|
|
158
|
-
- **Log calls never throw**: a failing `getLogLevel`, output, or data getter is swallowed; an invalid level falls back to `info`
|
|
159
|
-
- **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
|
|
160
|
-
- **No built-in redaction**: pass only data you are willing to log. `withTiming` logs `error.message` verbatim, so sanitize sensitive errors before throwing them
|
|
161
|
-
- **Synchronous outputs**: `LogOutput` is synchronous by design — async adapters manage their own promises
|
|
162
|
-
- **Lazy level evaluation**: `getLogLevel()` is called per-emit, so env changes are picked up without restart
|
|
163
|
-
- **Zero side effects**: Core module has zero module-level side effects (`sideEffects: false`)
|
|
181
|
+
## Related packages
|
|
164
182
|
|
|
165
|
-
|
|
183
|
+
None. This package has no runtime or peer dependencies, and no other @vllnt package shares code, a test or an example with it.
|
|
166
184
|
|
|
167
|
-
|
|
168
|
-
nothing is published from a local machine. Maintainers only.
|
|
185
|
+
## Contributing
|
|
169
186
|
|
|
170
|
-
|
|
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.
|
|
190
|
+
|
|
191
|
+
- Canary (`@canary`): every push to `main`, or a manual run on `main`, publishes one
|
|
171
192
|
(`pnpm add @vllnt/logger@canary`).
|
|
172
193
|
- Stable (`@latest`): merge a PR that sets `package.json` `version` and adds a matching
|
|
173
194
|
`## [X.Y.Z]` entry to `CHANGELOG.md`, then push the tag `vX.Y.Z` on that `main` commit.
|
|
174
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
|
+
|
|
175
205
|
## License
|
|
176
206
|
|
|
177
207
|
[MIT](LICENSE)
|
|
208
|
+
|
|
209
|
+
---
|
|
210
|
+
|
|
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 };
|