@vllnt/logger 0.1.2 → 0.1.3-canary.273f620

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 ADDED
@@ -0,0 +1,72 @@
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.1.3] - 2026-11-27
8
+
9
+ ### Added
10
+
11
+ - The npm package ships `docs/API.md` (every public export with an example), `llms.txt`,
12
+ `CHANGELOG.md` and the TypeScript sources in `src/`, so coding agents can read docs that match
13
+ the installed version from `node_modules/@vllnt/logger/`. `llms.txt` links the shipped files
14
+ with relative paths.
15
+ - README notes the bundled docs for coding agents and lists related packages.
16
+ - `package.json` sets `homepage` and `keywords`. Docs-only changes on `main` now publish a canary.
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.
31
+ - `withTiming` and `withTimingSync` no longer throw when `extraData` has a throwing getter: they
32
+ return the result or rethrow the original error, and drop only the entries that cannot be built.
33
+ - `docs/API.md`: the posthog-node wrapper now type-checks under `exactOptionalPropertyTypes`
34
+ (`(event, properties = {}) => client.capture({ distinctId, event, properties })`), and the
35
+ placeholder note names every placeholder. Tests type-check every example against the sources
36
+ and posthog-node, and check the entry-point table against the real exports.
37
+ - The publish workflow builds before it runs the tests, so the check of the built package files
38
+ runs before every publish instead of being skipped.
39
+
40
+ ### Changed
41
+
42
+ - `package.json` `exports` lists the `types` condition first so every resolver picks the typings.
43
+ - Publishing: stable releases come only from a pushed `vX.Y.Z` tag on `main` (npm trusted
44
+ publishing with provenance); canary builds still publish on every push to `main`. Actions are
45
+ pinned to commit SHAs, the workflow token is read-only by default, and pnpm is pinned to 10.34.8
46
+ with a seven-day minimum release age.
47
+ - README documents the release flow, serialization behaviour and that there is no built-in redaction.
48
+ - Built with tsup 9 and TypeScript 6. The `.d.ts` files of the subpaths and the shared core use
49
+ `export type { … }`, and the subpath declarations import shared types from `./index.js`. The
50
+ toolchain change does not change the types consumers see.
51
+ - Development only: `@vllnt/typescript` 3 (stricter compiler flags; published output unchanged),
52
+ `vitest` 5.1.1, and `pnpm test:coverage`.
53
+
54
+ ## [0.1.2] - 2026-03-10
55
+
56
+ ### Changed
57
+
58
+ - Publish workflow and CI refinements.
59
+
60
+ ## [0.1.1] - 2026-03-10
61
+
62
+ ### Changed
63
+
64
+ - Added the publish workflow (trusted publishing, canary and release jobs) and refined CI.
65
+
66
+ ## [0.1.0] - 2026-03-09
67
+
68
+ ### Added
69
+
70
+ - Initial release: core logger (`createLogger`, `createExtendedLogger`, `composeOutputs`,
71
+ `consoleOutput`, `formatLogEntry`, `parseLogLevel`), Node.js backend preset, and the `/convex`,
72
+ `/posthog` and `/testing` entry points.
package/README.md CHANGED
@@ -10,6 +10,12 @@ Zero runtime dependencies. Tree-shakeable. Works in Node.js, Convex, browser, an
10
10
  pnpm add @vllnt/logger
11
11
  ```
12
12
 
13
+ ## For coding agents
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
+
13
19
  ## Quick Start
14
20
 
15
21
  ```ts
@@ -27,15 +33,17 @@ Set `LOG_LEVEL` env var to control verbosity (`debug`, `info`, `warn`, `error`).
27
33
 
28
34
  ## Subpath Exports
29
35
 
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
+ | 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
42
 
37
43
  ## API
38
44
 
45
+ Full reference: [docs/API.md](docs/API.md).
46
+
39
47
  ### `createBackendLogger(scope): ExtendedLogger`
40
48
 
41
49
  Pre-configured for Node.js. Reads `LOG_LEVEL` from `process.env` lazily on each log call.
@@ -97,7 +105,7 @@ logger.info("started");
97
105
 
98
106
  ### `createPostHogOutput(capture): LogOutput`
99
107
 
100
- Wraps a PostHog-compatible `capture` function as a `LogOutput`. Swallows errors.
108
+ Wraps a PostHog-compatible `capture` function as a `LogOutput`. Swallows thrown errors and rejected promises.
101
109
 
102
110
  ```ts
103
111
  import { createPostHogOutput } from "@vllnt/logger/posthog";
@@ -125,21 +133,29 @@ expect(entries[0].event).toBe("test.hello");
125
133
 
126
134
  ### Utilities
127
135
 
128
- | Function | Description |
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) |
136
+ | Function | Description |
137
+ | ------------------------------------- | ---------------------------------------------------- |
138
+ | `formatLogEntry(level, event, data?)` | Build a `LogEntry` manually |
139
+ | `parseLogLevel(value, default?)` | Safe `string` to `LogLevel` parsing |
140
+ | `consoleOutput(entry)` | JSON to `console.debug/info/warn/error` (crash-safe) |
133
141
 
134
142
  ## Types
135
143
 
136
144
  ```ts
137
145
  type LogLevel = "debug" | "info" | "warn" | "error";
138
146
  type LogData = Record<string, unknown>;
139
- type LogEntry = { event: string; level: LogLevel; timestamp: string } & Record<string, unknown>;
147
+ type LogEntry = { event: string; level: LogLevel; timestamp: string } & Record<
148
+ string,
149
+ unknown
150
+ >;
140
151
  type LogOutput = (entry: LogEntry) => void;
141
- type Logger = { debug, info, warn, error: (event: string, data?: LogData) => void };
142
- type ExtendedLogger = Logger & { withTiming, withTimingSync };
152
+ type Logger = {
153
+ debug;
154
+ info;
155
+ warn;
156
+ error: (event: string, data?: LogData) => void;
157
+ };
158
+ type ExtendedLogger = Logger & { withTiming; withTimingSync };
143
159
  type LoggerConfig = { getLogLevel: () => LogLevel; output: LogOutput };
144
160
  ```
145
161
 
@@ -147,11 +163,35 @@ type LoggerConfig = { getLogLevel: () => LogLevel; output: LogOutput };
147
163
 
148
164
  - **Scoped events**: All events are prefixed with the logger scope (`auth.login`, `payments.charge`)
149
165
  - **Reserved field protection**: User data cannot overwrite `event`, `level`, or `timestamp`
150
- - **Crash-safe serialization**: `BigInt`, circular refs, and throwing `toJSON` are caught gracefully
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
151
169
  - **Synchronous outputs**: `LogOutput` is synchronous by design — async adapters manage their own promises
152
170
  - **Lazy level evaluation**: `getLogLevel()` is called per-emit, so env changes are picked up without restart
153
171
  - **Zero side effects**: Core module has zero module-level side effects (`sideEffects: false`)
154
172
 
173
+ ## Related packages
174
+
175
+ - [`@vllnt/analytics`](https://oss.vllnt.com/packages/analytics): product analytics with consent
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.
180
+
181
+ ## Releases
182
+
183
+ Every publish runs in `.github/workflows/publish.yml` with npm trusted publishing and provenance;
184
+ nothing is published from a local machine. Maintainers only.
185
+
186
+ - Canary (`@canary`): every push to `main` that touches the package publishes one
187
+ (`pnpm add @vllnt/logger@canary`).
188
+ - Stable (`@latest`): merge a PR that sets `package.json` `version` and adds a matching
189
+ `## [X.Y.Z]` entry to `CHANGELOG.md`, then push the tag `vX.Y.Z` on that `main` commit.
190
+
155
191
  ## License
156
192
 
157
193
  [MIT](LICENSE)
194
+
195
+ ---
196
+
197
+ Part of vllnt oss: https://oss.vllnt.com
@@ -23,10 +23,20 @@ function formatLogEntry(level, event, data) {
23
23
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
24
24
  };
25
25
  }
26
+ function resolveLevel(config) {
27
+ try {
28
+ return parseLogLevel(config.getLogLevel(), "info");
29
+ } catch {
30
+ return "info";
31
+ }
32
+ }
26
33
  function createLogger(scope, config) {
27
34
  const log = (level, event, data) => {
28
- if (shouldLog(level, config.getLogLevel())) {
29
- config.output(formatLogEntry(level, `${scope}.${event}`, data));
35
+ try {
36
+ if (shouldLog(level, resolveLevel(config))) {
37
+ config.output(formatLogEntry(level, `${scope}.${event}`, data));
38
+ }
39
+ } catch {
30
40
  }
31
41
  };
32
42
  return {
@@ -45,7 +55,17 @@ function createLogger(scope, config) {
45
55
  };
46
56
  }
47
57
  function formatError(error) {
48
- return error instanceof Error ? error.message : String(error);
58
+ try {
59
+ return error instanceof Error ? error.message : String(error);
60
+ } catch {
61
+ return "[unprintable error]";
62
+ }
63
+ }
64
+ function logBuilt(log, event, build) {
65
+ try {
66
+ log(event, build());
67
+ } catch {
68
+ }
49
69
  }
50
70
  function createWithTiming(base) {
51
71
  return async (label, execute, extraData) => {
@@ -53,17 +73,17 @@ function createWithTiming(base) {
53
73
  base.info(`${label}.start`, extraData);
54
74
  try {
55
75
  const result = await execute();
56
- base.info(`${label}.complete`, {
76
+ logBuilt(base.info, `${label}.complete`, () => ({
57
77
  ...extraData,
58
78
  durationMs: Date.now() - start
59
- });
79
+ }));
60
80
  return result;
61
81
  } catch (error) {
62
- base.error(`${label}.error`, {
82
+ logBuilt(base.error, `${label}.error`, () => ({
63
83
  ...extraData,
64
84
  durationMs: Date.now() - start,
65
85
  error: formatError(error)
66
- });
86
+ }));
67
87
  throw error;
68
88
  }
69
89
  };
@@ -74,17 +94,17 @@ function createWithTimingSync(base) {
74
94
  base.info(`${label}.start`, extraData);
75
95
  try {
76
96
  const result = execute();
77
- base.info(`${label}.complete`, {
97
+ logBuilt(base.info, `${label}.complete`, () => ({
78
98
  ...extraData,
79
99
  durationMs: Date.now() - start
80
- });
100
+ }));
81
101
  return result;
82
102
  } catch (error) {
83
- base.error(`${label}.error`, {
103
+ logBuilt(base.error, `${label}.error`, () => ({
84
104
  ...extraData,
85
105
  durationMs: Date.now() - start,
86
106
  error: formatError(error)
87
- });
107
+ }));
88
108
  throw error;
89
109
  }
90
110
  };
@@ -97,29 +117,50 @@ function createExtendedLogger(scope, config) {
97
117
  withTimingSync: createWithTimingSync(base)
98
118
  };
99
119
  }
120
+ function createReplacer() {
121
+ const ancestors = [];
122
+ return function replacer(_key, value) {
123
+ if (typeof value === "bigint") {
124
+ return value.toString();
125
+ }
126
+ const resolved = value instanceof Error ? { message: value.message, name: value.name, stack: value.stack } : value;
127
+ if (typeof resolved !== "object" || resolved === null) {
128
+ return resolved;
129
+ }
130
+ ancestors.splice(ancestors.indexOf(this) + 1);
131
+ if (ancestors.includes(resolved)) {
132
+ return "[Circular]";
133
+ }
134
+ ancestors.push(resolved);
135
+ return resolved;
136
+ };
137
+ }
100
138
  function consoleOutput(entry) {
101
139
  let message;
102
140
  try {
103
- message = JSON.stringify(entry);
141
+ message = JSON.stringify(entry, createReplacer());
104
142
  } catch {
105
143
  message = `[logger:serialize-error] event=${entry.event} level=${entry.level}`;
106
144
  }
107
- switch (entry.level) {
108
- case "debug":
109
- console.debug(message);
110
- break;
111
- case "error":
112
- console.error(message);
113
- break;
114
- case "info":
115
- console.info(message);
116
- break;
117
- case "warn":
118
- console.warn(message);
119
- break;
120
- default:
121
- console.info(message);
122
- break;
145
+ try {
146
+ switch (entry.level) {
147
+ case "debug":
148
+ console.debug(message);
149
+ break;
150
+ case "error":
151
+ console.error(message);
152
+ break;
153
+ case "info":
154
+ console.info(message);
155
+ break;
156
+ case "warn":
157
+ console.warn(message);
158
+ break;
159
+ default:
160
+ console.info(message);
161
+ break;
162
+ }
163
+ } catch {
123
164
  }
124
165
  }
125
166
  function composeOutputs(...outputs) {
package/dist/convex.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { b as LogLevel, E as ExtendedLogger } from './core-BKAGZb-m.js';
1
+ import { LogLevel, ExtendedLogger } from './index.js';
2
2
 
3
3
  /**
4
4
  * @vllnt/logger — Convex-safe logger.
package/dist/convex.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  consoleOutput,
3
3
  createExtendedLogger
4
- } from "./chunk-5GDAMA7T.js";
4
+ } from "./chunk-OROSOSC5.js";
5
5
 
6
6
  // src/convex.ts
7
7
  function createConvexLogger(scope, level = "info") {
@@ -41,7 +41,12 @@ declare function parseLogLevel(value: string | undefined, defaultLevel?: LogLeve
41
41
  * This prevents user data from overwriting event/level/timestamp.
42
42
  */
43
43
  declare function formatLogEntry(level: LogLevel, event: string, data?: LogData): LogEntry;
44
- /** Create a scoped logger with the given configuration. */
44
+ /**
45
+ * Create a scoped logger with the given configuration.
46
+ *
47
+ * Log calls never throw: a failing `getLogLevel`, `output`, or data getter is
48
+ * swallowed so logging cannot break the host application.
49
+ */
45
50
  declare function createLogger(scope: string, config: LoggerConfig): Logger;
46
51
  /**
47
52
  * Create an extended logger with timing helpers.
@@ -51,11 +56,13 @@ declare function createLogger(scope: string, config: LoggerConfig): Logger;
51
56
  */
52
57
  declare function createExtendedLogger(scope: string, config: LoggerConfig): ExtendedLogger;
53
58
  /**
54
- * Default console output handler. Crash-safe — wraps JSON.stringify
55
- * in try/catch to handle BigInt, circular refs, throwing toJSON.
59
+ * Default console output handler. Never throws. It handles BigInt, Error and
60
+ * circular values; anything still unserializable (throwing toJSON or getters)
61
+ * degrades to a minimal event/level line, and console failures disappear.
56
62
  */
57
63
  declare function consoleOutput(entry: LogEntry): void;
58
64
  /** Compose outputs into a single LogOutput. Each output runs in isolation. */
59
65
  declare function composeOutputs(...outputs: LogOutput[]): LogOutput;
60
66
 
61
- export { type ExtendedLogger as E, type LogData as L, type LogEntry as a, type LogLevel as b, type LogOutput as c, type Logger as d, type LoggerConfig as e, composeOutputs as f, consoleOutput as g, createExtendedLogger as h, createLogger as i, formatLogEntry as j, parseLogLevel as p };
67
+ export { composeOutputs as f, consoleOutput as g, createExtendedLogger as h, createLogger as i, formatLogEntry as j, parseLogLevel as p };
68
+ export type { ExtendedLogger as E, LogLevel as L, LogData as a, LogEntry as b, LogOutput as c, Logger as d, LoggerConfig as e };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as ExtendedLogger } from './core-BKAGZb-m.js';
2
- export { L as LogData, a as LogEntry, b 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-BKAGZb-m.js';
1
+ import { E as ExtendedLogger } from './core-he_ASnDU.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-he_ASnDU.js';
3
3
 
4
4
  /**
5
5
  * @vllnt/logger — Backend preset.
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ import {
5
5
  createLogger,
6
6
  formatLogEntry,
7
7
  parseLogLevel
8
- } from "./chunk-5GDAMA7T.js";
8
+ } from "./chunk-OROSOSC5.js";
9
9
 
10
10
  // src/backend.ts
11
11
  var HAS_PROCESS = typeof process !== "undefined";
package/dist/posthog.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { c as LogOutput } from './core-BKAGZb-m.js';
1
+ import { LogOutput } from './index.js';
2
2
 
3
3
  /**
4
4
  * @vllnt/logger — PostHog output adapter.
@@ -8,11 +8,13 @@ import { c as LogOutput } from './core-BKAGZb-m.js';
8
8
  */
9
9
 
10
10
  /** PostHog-compatible capture function signature */
11
- type PostHogCapture = (event: string, properties?: Record<string, unknown>) => void;
11
+ type PostHogCapture = (event: string, properties?: Record<string, unknown>) => unknown;
12
12
  /**
13
13
  * Create a LogOutput that forwards entries to PostHog.
14
- * Swallows errors from the capture function — logging must not break the app.
14
+ * Swallows errors from the capture function, including rejected promises it
15
+ * returns — logging must not break the app.
15
16
  */
16
17
  declare function createPostHogOutput(capture: PostHogCapture): LogOutput;
17
18
 
18
- export { type PostHogCapture, createPostHogOutput };
19
+ export { createPostHogOutput };
20
+ export type { PostHogCapture };
package/dist/posthog.js CHANGED
@@ -1,9 +1,16 @@
1
1
  // src/posthog.ts
2
+ function isThenable(value) {
3
+ return typeof value === "object" && value !== null && typeof value.then === "function";
4
+ }
2
5
  function createPostHogOutput(capture) {
3
6
  return (entry) => {
4
7
  try {
5
8
  const { event, ...properties } = entry;
6
- capture(event, properties);
9
+ const result = capture(event, properties);
10
+ if (isThenable(result)) {
11
+ Promise.resolve(result).catch(() => {
12
+ });
13
+ }
7
14
  } catch {
8
15
  }
9
16
  };
package/dist/testing.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as LogEntry, c as LogOutput } from './core-BKAGZb-m.js';
1
+ import { LogEntry, LogOutput } from './index.js';
2
2
 
3
3
  /**
4
4
  * @vllnt/logger — Test utilities.
@@ -14,4 +14,5 @@ type TestOutput = {
14
14
  /** Create a test output that captures entries into an array for assertion. */
15
15
  declare function createTestOutput(): TestOutput;
16
16
 
17
- export { type TestOutput, createTestOutput };
17
+ export { createTestOutput };
18
+ export type { TestOutput };
package/docs/API.md ADDED
@@ -0,0 +1,240 @@
1
+ # @vllnt/logger API
2
+
3
+ Reference for every public export. This file ships in the npm package, so the copy at
4
+ `node_modules/@vllnt/logger/docs/API.md` matches the installed version. The TypeScript sources
5
+ ship in `node_modules/@vllnt/logger/src/`.
6
+
7
+ ## Entry points
8
+
9
+ The package is ESM only (`import`; there is no `require` condition). Every entry point ships
10
+ its own type declarations.
11
+
12
+ | Import | Exports |
13
+ | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
14
+ | `@vllnt/logger` | `createBackendLogger`, `createLogger`, `createExtendedLogger`, `consoleOutput`, `composeOutputs`, `formatLogEntry`, `parseLogLevel`; types `LogLevel`, `LogData`, `LogEntry`, `LogOutput`, `Logger`, `ExtendedLogger`, `LoggerConfig` |
15
+ | `@vllnt/logger/convex` | `createConvexLogger` |
16
+ | `@vllnt/logger/posthog` | `createPostHogOutput`; type `PostHogCapture` |
17
+ | `@vllnt/logger/testing` | `createTestOutput`; type `TestOutput` |
18
+
19
+ Shared types (`LogEntry`, `LogLevel`, …) are exported only from `@vllnt/logger`.
20
+
21
+ Examples use placeholders (`posthog` for a posthog-js instance, `apiKey`, `distinctId`,
22
+ `fetchRows`, `orderId`) and Vitest's `expect`.
23
+
24
+ ## Behaviour shared by every logger
25
+
26
+ - The emitted `event` is `<scope>.<event>`: `createLogger("auth", …).info("login")` emits
27
+ `auth.login`.
28
+ - Levels by severity: `debug` < `info` < `warn` < `error`. An entry is emitted when its level is
29
+ at or above the configured level.
30
+ - `getLogLevel` runs on every log call. Its result goes through `parseLogLevel`; an invalid value
31
+ or a throw falls back to `info`.
32
+ - Log calls never throw. A throwing `getLogLevel`, output or data getter is swallowed.
33
+ - Data is spread first, then `event`, `level` and `timestamp` (ISO 8601), so data cannot
34
+ overwrite those three fields.
35
+ - Outputs are synchronous. There is no built-in redaction.
36
+
37
+ ## `@vllnt/logger`
38
+
39
+ ### `createBackendLogger(scope: string): ExtendedLogger`
40
+
41
+ Node.js preset. Reads `LOG_LEVEL` from `process.env` on each call, parsed with
42
+ `parseLogLevel(value, "warn")`, so the default is `warn`. Without `process` it uses `warn`.
43
+ Writes with `consoleOutput`.
44
+
45
+ ```ts
46
+ import { createBackendLogger } from "@vllnt/logger";
47
+
48
+ const logger = createBackendLogger("payments");
49
+ logger.warn("charge.declined", { amount: 99 });
50
+ // console.warn: {"amount":99,"event":"payments.charge.declined","level":"warn","timestamp":"..."}
51
+ ```
52
+
53
+ ### `createLogger(scope: string, config: LoggerConfig): Logger`
54
+
55
+ Core factory with your own level source and output.
56
+
57
+ ```ts
58
+ import { consoleOutput, createLogger } from "@vllnt/logger";
59
+
60
+ const logger = createLogger("api", {
61
+ getLogLevel: () => "debug",
62
+ output: consoleOutput,
63
+ });
64
+ logger.debug("request", { path: "/health" });
65
+ ```
66
+
67
+ ### `createExtendedLogger(scope: string, config: LoggerConfig): ExtendedLogger`
68
+
69
+ `createLogger` plus `withTiming` and `withTimingSync`:
70
+
71
+ - `withTiming<T>(label: string, execute: () => Promise<T>, extraData?: LogData): Promise<T>`
72
+ - `withTimingSync<T>(label: string, execute: () => T, extraData?: LogData): T`
73
+
74
+ Both log `info` `<scope>.<label>.start` with `extraData`, then `info` `<scope>.<label>.complete`
75
+ with `extraData` and `durationMs`. If `execute` throws, they log `error` `<scope>.<label>.error`
76
+ with `extraData`, `durationMs` and `error` (the `Error` message, otherwise `String(value)`, or
77
+ `"[unprintable error]"`), then rethrow the original error. The message is logged verbatim.
78
+
79
+ ```ts
80
+ import { consoleOutput, createExtendedLogger } from "@vllnt/logger";
81
+
82
+ const logger = createExtendedLogger("db", {
83
+ getLogLevel: () => "info",
84
+ output: consoleOutput,
85
+ });
86
+ const rows = await logger.withTiming("query", () => fetchRows(), { table: "users" });
87
+ // db.query.start, then db.query.complete with durationMs
88
+ ```
89
+
90
+ ### `consoleOutput(entry: LogEntry): void`
91
+
92
+ Default output. Writes `JSON.stringify(entry)` to `console.debug`, `console.info`,
93
+ `console.warn` or `console.error` by level. `BigInt` is written as a string, `Error` as
94
+ `{ name, message, stack }`, a circular reference as `"[Circular]"`. If serialization still fails
95
+ (a throwing `toJSON` or getter) it writes `[logger:serialize-error] event=<event> level=<level>`.
96
+ A throwing `console` method is swallowed.
97
+
98
+ ```ts
99
+ import { consoleOutput, formatLogEntry } from "@vllnt/logger";
100
+
101
+ consoleOutput(formatLogEntry("error", "job.failed", { error: new Error("timeout") }));
102
+ ```
103
+
104
+ ### `composeOutputs(...outputs: LogOutput[]): LogOutput`
105
+
106
+ Returns one output that calls each output in order. A throwing output does not stop the others.
107
+
108
+ ```ts
109
+ import { composeOutputs, consoleOutput } from "@vllnt/logger";
110
+ import { createPostHogOutput } from "@vllnt/logger/posthog";
111
+
112
+ const output = composeOutputs(consoleOutput, createPostHogOutput(posthog.capture.bind(posthog)));
113
+ ```
114
+
115
+ ### `formatLogEntry(level: LogLevel, event: string, data?: LogData): LogEntry`
116
+
117
+ Builds an entry: `{ ...data, event, level, timestamp }`. It does not add a scope prefix.
118
+
119
+ ```ts
120
+ import { formatLogEntry } from "@vllnt/logger";
121
+
122
+ formatLogEntry("info", "cache.hit", { key: "user:1" });
123
+ // { key: "user:1", event: "cache.hit", level: "info", timestamp: "2026-…Z" }
124
+ ```
125
+
126
+ ### `parseLogLevel(value: string | undefined, defaultLevel?: LogLevel): LogLevel`
127
+
128
+ Trims and lowercases `value`. Returns it when it is `debug`, `info`, `warn` or `error`, otherwise
129
+ `defaultLevel` (default `info`).
130
+
131
+ ```ts
132
+ import { parseLogLevel } from "@vllnt/logger";
133
+
134
+ parseLogLevel(" WARN "); // "warn"
135
+ parseLogLevel("verbose", "error"); // "error"
136
+ ```
137
+
138
+ ### Types
139
+
140
+ ```ts
141
+ type LogLevel = "debug" | "error" | "info" | "warn";
142
+ type LogData = Record<string, unknown>;
143
+ type LogEntry = { event: string; level: LogLevel; timestamp: string } & Record<string, unknown>;
144
+ type LogOutput = (entry: LogEntry) => void;
145
+
146
+ type Logger = {
147
+ debug: (event: string, data?: LogData) => void;
148
+ error: (event: string, data?: LogData) => void;
149
+ info: (event: string, data?: LogData) => void;
150
+ warn: (event: string, data?: LogData) => void;
151
+ };
152
+
153
+ type ExtendedLogger = Logger & {
154
+ withTiming: <T>(label: string, execute: () => Promise<T>, extraData?: LogData) => Promise<T>;
155
+ withTimingSync: <T>(label: string, execute: () => T, extraData?: LogData) => T;
156
+ };
157
+
158
+ type LoggerConfig = {
159
+ /** Called on every log call. */
160
+ getLogLevel: () => LogLevel;
161
+ output: LogOutput;
162
+ };
163
+ ```
164
+
165
+ ## `@vllnt/logger/convex`
166
+
167
+ ### `createConvexLogger(scope: string, level?: LogLevel): ExtendedLogger`
168
+
169
+ Logger for Convex queries, mutations and actions. Uses the fixed `level` (default `info`) and
170
+ `consoleOutput`. It does not read `process.env`.
171
+
172
+ ```ts
173
+ import { createConvexLogger } from "@vllnt/logger/convex";
174
+
175
+ const logger = createConvexLogger("orders", "debug");
176
+ logger.info("created", { orderId });
177
+ ```
178
+
179
+ ## `@vllnt/logger/posthog`
180
+
181
+ ### `createPostHogOutput(capture: PostHogCapture): LogOutput`
182
+
183
+ Calls `capture(entry.event, properties)`, where `properties` is the entry without `event`
184
+ (`level`, `timestamp` and your data). Errors thrown by `capture`, and rejections of a promise it
185
+ returns, are swallowed. No PostHog SDK dependency: pass your own function. posthog-js
186
+ `capture(event, properties)` fits as is:
187
+
188
+ ```ts
189
+ import { createLogger } from "@vllnt/logger";
190
+ import { createPostHogOutput } from "@vllnt/logger/posthog";
191
+
192
+ const logger = createLogger("billing", {
193
+ getLogLevel: () => "info",
194
+ output: createPostHogOutput((event, properties) => posthog.capture(event, properties)),
195
+ });
196
+ ```
197
+
198
+ posthog-node `capture` takes one object, so wrap it. The `= {}` default keeps the wrapper valid
199
+ under `exactOptionalPropertyTypes`, where posthog-node's `properties` does not accept `undefined`:
200
+
201
+ ```ts
202
+ import { createPostHogOutput } from "@vllnt/logger/posthog";
203
+ import { PostHog } from "posthog-node";
204
+
205
+ const client = new PostHog(apiKey);
206
+ const output = createPostHogOutput((event, properties = {}) =>
207
+ client.capture({ distinctId, event, properties }),
208
+ );
209
+ ```
210
+
211
+ ### `PostHogCapture`
212
+
213
+ ```ts
214
+ type PostHogCapture = (event: string, properties?: Record<string, unknown>) => unknown;
215
+ ```
216
+
217
+ ## `@vllnt/logger/testing`
218
+
219
+ ### `createTestOutput(): TestOutput`
220
+
221
+ An output that stores every entry in `entries`, for assertions.
222
+
223
+ ```ts
224
+ import { createLogger } from "@vllnt/logger";
225
+ import { createTestOutput } from "@vllnt/logger/testing";
226
+
227
+ const { entries, output } = createTestOutput();
228
+ const logger = createLogger("test", { getLogLevel: () => "debug", output });
229
+ logger.info("hello", { a: 1 });
230
+ expect(entries[0]).toMatchObject({ event: "test.hello", level: "info", a: 1 });
231
+ ```
232
+
233
+ ### `TestOutput`
234
+
235
+ ```ts
236
+ type TestOutput = {
237
+ entries: readonly LogEntry[];
238
+ output: LogOutput;
239
+ };
240
+ ```
package/llms.txt ADDED
@@ -0,0 +1,33 @@
1
+ # @vllnt/logger
2
+
3
+ > Small structured logging package for the @vllnt ecosystem. Emits JSON log entries, has zero runtime dependencies, and never throws from a log call.
4
+
5
+ Scoped events (`auth.login`), levels `debug`, `info`, `warn`, `error`, and pluggable synchronous outputs. The Node.js backend preset reads `LOG_LEVEL` from `process.env` on each call and defaults to `warn`. There is no built-in redaction. ESM only.
6
+
7
+ ## For coding agents
8
+
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
+
11
+ ## Docs
12
+
13
+ - [API Reference](./docs/API.md): Every public export, its signature and an example, per entry point
14
+ - [README](./README.md): Install, quick start, entry points and design decisions
15
+ - [Changelog](./CHANGELOG.md): Version history and release notes
16
+
17
+ ## Entry points
18
+
19
+ - `@vllnt/logger`: core API and Node.js backend preset (`createBackendLogger`)
20
+ - `@vllnt/logger/convex`: `createConvexLogger`, no `process.env` access
21
+ - `@vllnt/logger/posthog`: `createPostHogOutput`
22
+ - `@vllnt/logger/testing`: `createTestOutput`
23
+
24
+ ## Ecosystem
25
+
26
+ - [vllnt oss](https://oss.vllnt.com/llms.txt): Index of all @vllnt open-source packages
27
+
28
+ ## Optional
29
+
30
+ - [Contributing](https://github.com/vllnt/logger/blob/main/CONTRIBUTING.md): Development setup and release flow
31
+ - [AGENTS](https://github.com/vllnt/logger/blob/main/AGENTS.md): Agent instructions for working on this repository (not shipped in the package)
32
+ - [Security Policy](https://github.com/vllnt/logger/blob/main/SECURITY.md): Vulnerability reporting
33
+ - [License](./LICENSE): MIT
package/package.json CHANGED
@@ -1,56 +1,89 @@
1
1
  {
2
2
  "name": "@vllnt/logger",
3
- "version": "0.1.2",
3
+ "version": "0.1.3-canary.273f620",
4
4
  "type": "module",
5
5
  "description": "Structured logging for the @vllnt ecosystem",
6
6
  "license": "MIT",
7
7
  "author": "bntvllnt",
8
+ "homepage": "https://oss.vllnt.com/packages/logger",
8
9
  "repository": {
9
10
  "type": "git",
10
11
  "url": "https://github.com/vllnt/logger"
11
12
  },
13
+ "keywords": [
14
+ "logger",
15
+ "logging",
16
+ "structured-logging",
17
+ "json",
18
+ "convex",
19
+ "posthog",
20
+ "typescript",
21
+ "zero-dependency"
22
+ ],
12
23
  "sideEffects": false,
13
24
  "exports": {
14
25
  ".": {
15
- "import": "./dist/index.js",
16
- "types": "./dist/index.d.ts"
26
+ "types": "./dist/index.d.ts",
27
+ "import": "./dist/index.js"
17
28
  },
18
29
  "./convex": {
19
- "import": "./dist/convex.js",
20
- "types": "./dist/convex.d.ts"
30
+ "types": "./dist/convex.d.ts",
31
+ "import": "./dist/convex.js"
21
32
  },
22
33
  "./posthog": {
23
- "import": "./dist/posthog.js",
24
- "types": "./dist/posthog.d.ts"
34
+ "types": "./dist/posthog.d.ts",
35
+ "import": "./dist/posthog.js"
25
36
  },
26
37
  "./testing": {
27
- "import": "./dist/testing.js",
28
- "types": "./dist/testing.d.ts"
38
+ "types": "./dist/testing.d.ts",
39
+ "import": "./dist/testing.js"
29
40
  }
30
41
  },
31
42
  "files": [
32
- "dist"
43
+ "dist",
44
+ "src",
45
+ "docs/API.md",
46
+ "CHANGELOG.md",
47
+ "llms.txt"
33
48
  ],
49
+ "scripts": {
50
+ "build": "tsup",
51
+ "check-types": "tsc --noEmit --incremental --tsBuildInfoFile node_modules/.cache/tsc/check-types.tsbuildinfo",
52
+ "lint": "eslint --cache --cache-location node_modules/.cache/eslint/ --max-warnings 0",
53
+ "lint:fix": "eslint --cache --cache-location node_modules/.cache/eslint/ --fix",
54
+ "test": "vitest run",
55
+ "test:coverage": "vitest run --coverage --coverage.include=src --coverage.reporter=text",
56
+ "test:watch": "vitest"
57
+ },
34
58
  "publishConfig": {
35
59
  "access": "public",
36
60
  "registry": "https://registry.npmjs.org/"
37
61
  },
38
62
  "devDependencies": {
39
- "@types/node": "^22.15.3",
40
- "@vllnt/eslint-config": "^1.0.0",
41
- "@vllnt/typescript": "^1.0.0",
42
- "eslint": "^9.39.4",
43
- "prettier": "^3.8.1",
44
- "tsup": "^8.4.0",
45
- "typescript": "^5.9.3",
46
- "vitest": "^3.1.1"
63
+ "@types/node": "^26.6.6",
64
+ "@vitest/coverage-v8": "^5.1.1",
65
+ "@vllnt/eslint-config": "^2.1.0",
66
+ "@vllnt/typescript": "^3.0.0",
67
+ "eslint": "^9.39.5",
68
+ "posthog-node": "^6.0.5",
69
+ "prettier": "^3.10.1",
70
+ "tsup": "^9.0.0",
71
+ "typescript": "^6.0.3",
72
+ "vitest": "^5.1.1"
47
73
  },
48
- "scripts": {
49
- "build": "tsup",
50
- "check-types": "tsc --noEmit",
51
- "lint": "eslint --max-warnings 0",
52
- "lint:fix": "eslint --fix",
53
- "test": "vitest run",
54
- "test:watch": "vitest"
74
+ "packageManager": "pnpm@10.34.8",
75
+ "pnpm": {
76
+ "minimumReleaseAge": 10080,
77
+ "minimumReleaseAgeExclude": [
78
+ "@vllnt/*"
79
+ ],
80
+ "ignoredBuiltDependencies": [
81
+ "esbuild"
82
+ ],
83
+ "overrides": {
84
+ "minimatch@>=7.0.0 <11.0.1": "11.0.5",
85
+ "deepmerge-ts@<8.0.0": "^8.0.0",
86
+ "handlebars@<4.7.10": "^4.7.10"
87
+ }
55
88
  }
56
- }
89
+ }
package/src/backend.ts ADDED
@@ -0,0 +1,35 @@
1
+ /**
2
+ * @vllnt/logger — Backend preset.
3
+ *
4
+ * Pre-configured logger for Node.js backends.
5
+ * Reads LOG_LEVEL from process.env on each call (no module-level side effects).
6
+ */
7
+
8
+ import {
9
+ consoleOutput,
10
+ createExtendedLogger,
11
+ type ExtendedLogger,
12
+ type LogLevel,
13
+ parseLogLevel,
14
+ } from "./core.js";
15
+
16
+ const HAS_PROCESS = typeof process !== "undefined";
17
+
18
+ function getEnvironmentVariable(key: string): string | undefined {
19
+ if (HAS_PROCESS && process.env) {
20
+ return process.env[key];
21
+ }
22
+ return undefined;
23
+ }
24
+
25
+ function getBackendLogLevel(): LogLevel {
26
+ return parseLogLevel(getEnvironmentVariable("LOG_LEVEL"), "warn");
27
+ }
28
+
29
+ /** Create a scoped backend logger. Reads LOG_LEVEL from process.env on each call. */
30
+ export function createBackendLogger(scope: string): ExtendedLogger {
31
+ return createExtendedLogger(scope, {
32
+ getLogLevel: getBackendLogLevel,
33
+ output: consoleOutput,
34
+ });
35
+ }
package/src/convex.ts ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * @vllnt/logger — Convex-safe logger.
3
+ *
4
+ * Imports from core.ts (no process.env, no crypto).
5
+ * Works in Convex queries, mutations, and actions.
6
+ */
7
+
8
+ import {
9
+ consoleOutput,
10
+ createExtendedLogger,
11
+ type ExtendedLogger,
12
+ type LogLevel,
13
+ } from "./core.js";
14
+
15
+ /**
16
+ * Create a logger for Convex functions.
17
+ * Pass level explicitly (Convex has no process.env in queries/mutations).
18
+ * Defaults to "info".
19
+ */
20
+ export function createConvexLogger(
21
+ scope: string,
22
+ level: LogLevel = "info",
23
+ ): ExtendedLogger {
24
+ return createExtendedLogger(scope, {
25
+ getLogLevel: () => level,
26
+ output: consoleOutput,
27
+ });
28
+ }
package/src/core.ts ADDED
@@ -0,0 +1,309 @@
1
+ /**
2
+ * @vllnt/logger — Core module.
3
+ *
4
+ * Pure functions, ZERO module-level side effects.
5
+ * Safe to import in any runtime (Node, Convex, browser, edge).
6
+ */
7
+
8
+ /** Log levels ordered by severity */
9
+ export type LogLevel = "debug" | "error" | "info" | "warn";
10
+
11
+ /** Structured log data payload */
12
+ export type LogData = Record<string, unknown>;
13
+
14
+ /** Formatted log entry */
15
+ export type LogEntry = {
16
+ event: string;
17
+ level: LogLevel;
18
+ timestamp: string;
19
+ } & Record<string, unknown>;
20
+
21
+ /** Logger interface — 4 level methods */
22
+ export type Logger = {
23
+ debug: (event: string, data?: LogData) => void;
24
+ error: (event: string, data?: LogData) => void;
25
+ info: (event: string, data?: LogData) => void;
26
+ warn: (event: string, data?: LogData) => void;
27
+ };
28
+
29
+ /** Extended logger with timing helpers */
30
+ export type ExtendedLogger = Logger & {
31
+ withTiming: <T>(
32
+ label: string,
33
+ execute: () => Promise<T>,
34
+ extraData?: LogData,
35
+ ) => Promise<T>;
36
+ withTimingSync: <T>(
37
+ label: string,
38
+ execute: () => T,
39
+ extraData?: LogData,
40
+ ) => T;
41
+ };
42
+
43
+ /** Output handler for log entries. Synchronous by design — async adapters must handle their own promises. */
44
+ export type LogOutput = (entry: LogEntry) => void;
45
+
46
+ /** Configuration for creating a logger */
47
+ export type LoggerConfig = {
48
+ /** Returns the current log level. Called on every log emit — keep it cheap. */
49
+ getLogLevel: () => LogLevel;
50
+ output: LogOutput;
51
+ };
52
+
53
+ const LOG_LEVEL_PRIORITY: Record<LogLevel, number> = {
54
+ debug: 0,
55
+ error: 3,
56
+ info: 1,
57
+ warn: 2,
58
+ };
59
+
60
+ function shouldLog(level: LogLevel, configuredLevel: LogLevel): boolean {
61
+ return LOG_LEVEL_PRIORITY[level] >= LOG_LEVEL_PRIORITY[configuredLevel];
62
+ }
63
+
64
+ /** Parse a log level string, returning default if invalid. */
65
+ export function parseLogLevel(
66
+ value: string | undefined,
67
+ defaultLevel: LogLevel = "info",
68
+ ): LogLevel {
69
+ const normalized = value?.toLowerCase().trim();
70
+ if (
71
+ normalized === "debug" ||
72
+ normalized === "info" ||
73
+ normalized === "warn" ||
74
+ normalized === "error"
75
+ ) {
76
+ return normalized;
77
+ }
78
+ return defaultLevel;
79
+ }
80
+
81
+ /**
82
+ * Format a log entry. User data spread FIRST, fixed fields LAST.
83
+ * This prevents user data from overwriting event/level/timestamp.
84
+ */
85
+ export function formatLogEntry(
86
+ level: LogLevel,
87
+ event: string,
88
+ data?: LogData,
89
+ ): LogEntry {
90
+ return {
91
+ ...data,
92
+ event,
93
+ level,
94
+ timestamp: new Date().toISOString(),
95
+ };
96
+ }
97
+
98
+ /** Resolve the configured level; a throwing or invalid `getLogLevel` falls back to "info". */
99
+ function resolveLevel(config: LoggerConfig): LogLevel {
100
+ try {
101
+ return parseLogLevel(config.getLogLevel(), "info");
102
+ } catch {
103
+ return "info";
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Create a scoped logger with the given configuration.
109
+ *
110
+ * Log calls never throw: a failing `getLogLevel`, `output`, or data getter is
111
+ * swallowed so logging cannot break the host application.
112
+ */
113
+ export function createLogger(scope: string, config: LoggerConfig): Logger {
114
+ const log = (level: LogLevel, event: string, data?: LogData): void => {
115
+ try {
116
+ if (shouldLog(level, resolveLevel(config))) {
117
+ config.output(formatLogEntry(level, `${scope}.${event}`, data));
118
+ }
119
+ } catch {
120
+ // Swallowed — logging failures must not propagate
121
+ }
122
+ };
123
+
124
+ return {
125
+ debug: (event, data) => {
126
+ log("debug", event, data);
127
+ },
128
+ error: (event, data) => {
129
+ log("error", event, data);
130
+ },
131
+ info: (event, data) => {
132
+ log("info", event, data);
133
+ },
134
+ warn: (event, data) => {
135
+ log("warn", event, data);
136
+ },
137
+ };
138
+ }
139
+
140
+ function formatError(error: unknown): string {
141
+ try {
142
+ return error instanceof Error ? error.message : String(error);
143
+ } catch {
144
+ return "[unprintable error]";
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Build the data and log it. If building throws (for example a throwing
150
+ * getter in `extraData`), drop the entry, as `createLogger` does.
151
+ */
152
+ function logBuilt(
153
+ log: Logger["info"],
154
+ event: string,
155
+ build: () => LogData,
156
+ ): void {
157
+ try {
158
+ log(event, build());
159
+ } catch {
160
+ // Dropped — building the data must not break the timed call
161
+ }
162
+ }
163
+
164
+ function createWithTiming(base: Logger): ExtendedLogger["withTiming"] {
165
+ return async <T>(
166
+ label: string,
167
+ execute: () => Promise<T>,
168
+ extraData?: LogData,
169
+ ): Promise<T> => {
170
+ const start = Date.now();
171
+ base.info(`${label}.start`, extraData);
172
+ try {
173
+ const result = await execute();
174
+ logBuilt(base.info, `${label}.complete`, () => ({
175
+ ...extraData,
176
+ durationMs: Date.now() - start,
177
+ }));
178
+ return result;
179
+ } catch (error) {
180
+ logBuilt(base.error, `${label}.error`, () => ({
181
+ ...extraData,
182
+ durationMs: Date.now() - start,
183
+ error: formatError(error),
184
+ }));
185
+ throw error;
186
+ }
187
+ };
188
+ }
189
+
190
+ function createWithTimingSync(base: Logger): ExtendedLogger["withTimingSync"] {
191
+ return <T>(label: string, execute: () => T, extraData?: LogData): T => {
192
+ const start = Date.now();
193
+ base.info(`${label}.start`, extraData);
194
+ try {
195
+ const result = execute();
196
+ logBuilt(base.info, `${label}.complete`, () => ({
197
+ ...extraData,
198
+ durationMs: Date.now() - start,
199
+ }));
200
+ return result;
201
+ } catch (error) {
202
+ logBuilt(base.error, `${label}.error`, () => ({
203
+ ...extraData,
204
+ durationMs: Date.now() - start,
205
+ error: formatError(error),
206
+ }));
207
+ throw error;
208
+ }
209
+ };
210
+ }
211
+
212
+ /**
213
+ * Create an extended logger with timing helpers.
214
+ *
215
+ * @remarks Caught errors use `error.message` verbatim.
216
+ * Callers handling sensitive errors should sanitize before throwing.
217
+ */
218
+ export function createExtendedLogger(
219
+ scope: string,
220
+ config: LoggerConfig,
221
+ ): ExtendedLogger {
222
+ const base = createLogger(scope, config);
223
+ return {
224
+ ...base,
225
+ withTiming: createWithTiming(base),
226
+ withTimingSync: createWithTimingSync(base),
227
+ };
228
+ }
229
+
230
+ /**
231
+ * JSON.stringify replacer that keeps entries serializable. It turns BigInt
232
+ * into a string, Error into `{ name, message, stack }`, and circular
233
+ * references into "[Circular]". Repeated non-circular references stay intact.
234
+ */
235
+ function createReplacer(): (
236
+ this: unknown,
237
+ key: string,
238
+ value: unknown,
239
+ ) => unknown {
240
+ const ancestors: unknown[] = [];
241
+ return function replacer(this: unknown, _key: string, value: unknown) {
242
+ if (typeof value === "bigint") {
243
+ return value.toString();
244
+ }
245
+ const resolved =
246
+ value instanceof Error
247
+ ? { message: value.message, name: value.name, stack: value.stack }
248
+ : value;
249
+ if (typeof resolved !== "object" || resolved === null) {
250
+ return resolved;
251
+ }
252
+ // Drop everything below the current holder: the rest is a finished sibling branch.
253
+ ancestors.splice(ancestors.indexOf(this) + 1);
254
+ if (ancestors.includes(resolved)) {
255
+ return "[Circular]";
256
+ }
257
+ ancestors.push(resolved);
258
+ return resolved;
259
+ };
260
+ }
261
+
262
+ /**
263
+ * Default console output handler. Never throws. It handles BigInt, Error and
264
+ * circular values; anything still unserializable (throwing toJSON or getters)
265
+ * degrades to a minimal event/level line, and console failures disappear.
266
+ */
267
+ export function consoleOutput(entry: LogEntry): void {
268
+ let message: string;
269
+ try {
270
+ message = JSON.stringify(entry, createReplacer());
271
+ } catch {
272
+ message = `[logger:serialize-error] event=${entry.event} level=${entry.level}`;
273
+ }
274
+
275
+ try {
276
+ switch (entry.level) {
277
+ case "debug":
278
+ console.debug(message);
279
+ break;
280
+ case "error":
281
+ console.error(message);
282
+ break;
283
+ case "info":
284
+ console.info(message);
285
+ break;
286
+ case "warn":
287
+ console.warn(message);
288
+ break;
289
+ default:
290
+ console.info(message);
291
+ break;
292
+ }
293
+ } catch {
294
+ // Swallowed — a broken console must not break the app
295
+ }
296
+ }
297
+
298
+ /** Compose outputs into a single LogOutput. Each output runs in isolation. */
299
+ export function composeOutputs(...outputs: LogOutput[]): LogOutput {
300
+ return (entry: LogEntry): void => {
301
+ outputs.forEach((output) => {
302
+ try {
303
+ output(entry);
304
+ } catch {
305
+ // Isolated — other outputs continue
306
+ }
307
+ });
308
+ };
309
+ }
package/src/index.ts ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @vllnt/logger — Structured logging for the @vllnt ecosystem.
3
+ *
4
+ * Core exports + backend preset.
5
+ */
6
+
7
+ export { createBackendLogger } from "./backend.js";
8
+ export {
9
+ composeOutputs,
10
+ consoleOutput,
11
+ createExtendedLogger,
12
+ createLogger,
13
+ type ExtendedLogger,
14
+ formatLogEntry,
15
+ type LogData,
16
+ type LogEntry,
17
+ type Logger,
18
+ type LoggerConfig,
19
+ type LogLevel,
20
+ type LogOutput,
21
+ parseLogLevel,
22
+ } from "./core.js";
package/src/posthog.ts ADDED
@@ -0,0 +1,43 @@
1
+ /**
2
+ * @vllnt/logger — PostHog output adapter.
3
+ *
4
+ * Wraps a PostHog-style capture function as a LogOutput.
5
+ * No PostHog SDK dependency — consumer passes their own capture fn.
6
+ */
7
+
8
+ import type { LogEntry, LogOutput } from "./core.js";
9
+
10
+ /** PostHog-compatible capture function signature */
11
+ export type PostHogCapture = (
12
+ event: string,
13
+ properties?: Record<string, unknown>,
14
+ ) => unknown;
15
+
16
+ function isThenable(value: unknown): value is PromiseLike<unknown> {
17
+ return (
18
+ typeof value === "object" &&
19
+ value !== null &&
20
+ typeof (value as { then?: unknown }).then === "function"
21
+ );
22
+ }
23
+
24
+ /**
25
+ * Create a LogOutput that forwards entries to PostHog.
26
+ * Swallows errors from the capture function, including rejected promises it
27
+ * returns — logging must not break the app.
28
+ */
29
+ export function createPostHogOutput(capture: PostHogCapture): LogOutput {
30
+ return (entry: LogEntry): void => {
31
+ try {
32
+ const { event, ...properties } = entry;
33
+ const result = capture(event, properties);
34
+ if (isThenable(result)) {
35
+ Promise.resolve(result).catch(() => {
36
+ // Swallowed — async capture failures must not become unhandled rejections
37
+ });
38
+ }
39
+ } catch {
40
+ // Swallowed — logging failures must not propagate
41
+ }
42
+ };
43
+ }
package/src/testing.ts ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @vllnt/logger — Test utilities.
3
+ *
4
+ * Provides a test output that captures log entries for assertion.
5
+ */
6
+
7
+ import type { LogEntry, LogOutput } from "./core.js";
8
+
9
+ /** Result of createTestOutput — output function + captured entries */
10
+ export type TestOutput = {
11
+ entries: readonly LogEntry[];
12
+ output: LogOutput;
13
+ };
14
+
15
+ /** Create a test output that captures entries into an array for assertion. */
16
+ export function createTestOutput(): TestOutput {
17
+ const entries: LogEntry[] = [];
18
+ const output: LogOutput = (entry: LogEntry): void => {
19
+ entries.push(entry);
20
+ };
21
+ return { entries, output };
22
+ }