@vllnt/logger 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 bntvllnt
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,157 @@
1
+ # @vllnt/logger
2
+
3
+ Structured JSON logging for the [@vllnt](https://github.com/vllnt) ecosystem.
4
+
5
+ Zero runtime dependencies. Tree-shakeable. Works in Node.js, Convex, browser, and edge runtimes.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pnpm add @vllnt/logger
11
+ ```
12
+
13
+ ## Quick Start
14
+
15
+ ```ts
16
+ import { createBackendLogger } from "@vllnt/logger";
17
+
18
+ const logger = createBackendLogger("auth");
19
+
20
+ logger.info("login", { userId: "123" });
21
+ // → {"event":"auth.login","level":"info","timestamp":"...","userId":"123"}
22
+
23
+ logger.warn("rate-limited", { ip: "1.2.3.4" });
24
+ ```
25
+
26
+ Set `LOG_LEVEL` env var to control verbosity (`debug`, `info`, `warn`, `error`). Defaults to `warn`.
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
+
37
+ ## API
38
+
39
+ ### `createBackendLogger(scope): ExtendedLogger`
40
+
41
+ Pre-configured for Node.js. Reads `LOG_LEVEL` from `process.env` lazily on each log call.
42
+
43
+ ```ts
44
+ const logger = createBackendLogger("payments");
45
+ logger.info("charge", { amount: 99, currency: "usd" });
46
+ ```
47
+
48
+ ### `createLogger(scope, config): Logger`
49
+
50
+ Core factory. Bring your own level strategy and output.
51
+
52
+ ```ts
53
+ import { createLogger, consoleOutput } from "@vllnt/logger";
54
+
55
+ const logger = createLogger("api", {
56
+ getLogLevel: () => "debug",
57
+ output: consoleOutput,
58
+ });
59
+ ```
60
+
61
+ ### `createExtendedLogger(scope, config): ExtendedLogger`
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.
76
+
77
+ ```ts
78
+ import { composeOutputs, consoleOutput } from "@vllnt/logger";
79
+ import { createPostHogOutput } from "@vllnt/logger/posthog";
80
+
81
+ const output = composeOutputs(
82
+ consoleOutput,
83
+ createPostHogOutput(posthog.capture.bind(posthog)),
84
+ );
85
+ ```
86
+
87
+ ### `createConvexLogger(scope, level?): ExtendedLogger`
88
+
89
+ Safe for Convex queries, mutations, and actions. No `process.env` access.
90
+
91
+ ```ts
92
+ import { createConvexLogger } from "@vllnt/logger/convex";
93
+
94
+ const logger = createConvexLogger("myFunction", "debug");
95
+ logger.info("started");
96
+ ```
97
+
98
+ ### `createPostHogOutput(capture): LogOutput`
99
+
100
+ Wraps a PostHog-compatible `capture` function as a `LogOutput`. Swallows errors.
101
+
102
+ ```ts
103
+ import { createPostHogOutput } from "@vllnt/logger/posthog";
104
+
105
+ const output = createPostHogOutput(posthog.capture.bind(posthog));
106
+ ```
107
+
108
+ ### `createTestOutput(): TestOutput`
109
+
110
+ Captures log entries in-memory for test assertions.
111
+
112
+ ```ts
113
+ import { createTestOutput } from "@vllnt/logger/testing";
114
+ import { createLogger } from "@vllnt/logger";
115
+
116
+ const { entries, output } = createTestOutput();
117
+ const logger = createLogger("test", {
118
+ getLogLevel: () => "debug",
119
+ output,
120
+ });
121
+
122
+ logger.info("hello", { a: 1 });
123
+ expect(entries[0].event).toBe("test.hello");
124
+ ```
125
+
126
+ ### Utilities
127
+
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) |
133
+
134
+ ## Types
135
+
136
+ ```ts
137
+ type LogLevel = "debug" | "info" | "warn" | "error";
138
+ type LogData = Record<string, unknown>;
139
+ type LogEntry = { event: string; level: LogLevel; timestamp: string } & Record<string, unknown>;
140
+ type LogOutput = (entry: LogEntry) => void;
141
+ type Logger = { debug, info, warn, error: (event: string, data?: LogData) => void };
142
+ type ExtendedLogger = Logger & { withTiming, withTimingSync };
143
+ type LoggerConfig = { getLogLevel: () => LogLevel; output: LogOutput };
144
+ ```
145
+
146
+ ## Design Decisions
147
+
148
+ - **Scoped events**: All events are prefixed with the logger scope (`auth.login`, `payments.charge`)
149
+ - **Reserved field protection**: User data cannot overwrite `event`, `level`, or `timestamp`
150
+ - **Crash-safe serialization**: `BigInt`, circular refs, and throwing `toJSON` are caught gracefully
151
+ - **Synchronous outputs**: `LogOutput` is synchronous by design — async adapters manage their own promises
152
+ - **Lazy level evaluation**: `getLogLevel()` is called per-emit, so env changes are picked up without restart
153
+ - **Zero side effects**: Core module has zero module-level side effects (`sideEffects: false`)
154
+
155
+ ## License
156
+
157
+ [MIT](LICENSE)
@@ -0,0 +1,143 @@
1
+ // src/core.ts
2
+ var LOG_LEVEL_PRIORITY = {
3
+ debug: 0,
4
+ error: 3,
5
+ info: 1,
6
+ warn: 2
7
+ };
8
+ function shouldLog(level, configuredLevel) {
9
+ return LOG_LEVEL_PRIORITY[level] >= LOG_LEVEL_PRIORITY[configuredLevel];
10
+ }
11
+ function parseLogLevel(value, defaultLevel = "info") {
12
+ const normalized = value?.toLowerCase().trim();
13
+ if (normalized === "debug" || normalized === "info" || normalized === "warn" || normalized === "error") {
14
+ return normalized;
15
+ }
16
+ return defaultLevel;
17
+ }
18
+ function formatLogEntry(level, event, data) {
19
+ return {
20
+ ...data,
21
+ event,
22
+ level,
23
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
24
+ };
25
+ }
26
+ function createLogger(scope, config) {
27
+ const log = (level, event, data) => {
28
+ if (shouldLog(level, config.getLogLevel())) {
29
+ config.output(formatLogEntry(level, `${scope}.${event}`, data));
30
+ }
31
+ };
32
+ return {
33
+ debug: (event, data) => {
34
+ log("debug", event, data);
35
+ },
36
+ error: (event, data) => {
37
+ log("error", event, data);
38
+ },
39
+ info: (event, data) => {
40
+ log("info", event, data);
41
+ },
42
+ warn: (event, data) => {
43
+ log("warn", event, data);
44
+ }
45
+ };
46
+ }
47
+ function formatError(error) {
48
+ return error instanceof Error ? error.message : String(error);
49
+ }
50
+ function createWithTiming(base) {
51
+ return async (label, execute, extraData) => {
52
+ const start = Date.now();
53
+ base.info(`${label}.start`, extraData);
54
+ try {
55
+ const result = await execute();
56
+ base.info(`${label}.complete`, {
57
+ ...extraData,
58
+ durationMs: Date.now() - start
59
+ });
60
+ return result;
61
+ } catch (error) {
62
+ base.error(`${label}.error`, {
63
+ ...extraData,
64
+ durationMs: Date.now() - start,
65
+ error: formatError(error)
66
+ });
67
+ throw error;
68
+ }
69
+ };
70
+ }
71
+ function createWithTimingSync(base) {
72
+ return (label, execute, extraData) => {
73
+ const start = Date.now();
74
+ base.info(`${label}.start`, extraData);
75
+ try {
76
+ const result = execute();
77
+ base.info(`${label}.complete`, {
78
+ ...extraData,
79
+ durationMs: Date.now() - start
80
+ });
81
+ return result;
82
+ } catch (error) {
83
+ base.error(`${label}.error`, {
84
+ ...extraData,
85
+ durationMs: Date.now() - start,
86
+ error: formatError(error)
87
+ });
88
+ throw error;
89
+ }
90
+ };
91
+ }
92
+ function createExtendedLogger(scope, config) {
93
+ const base = createLogger(scope, config);
94
+ return {
95
+ ...base,
96
+ withTiming: createWithTiming(base),
97
+ withTimingSync: createWithTimingSync(base)
98
+ };
99
+ }
100
+ function consoleOutput(entry) {
101
+ let message;
102
+ try {
103
+ message = JSON.stringify(entry);
104
+ } catch {
105
+ message = `[logger:serialize-error] event=${entry.event} level=${entry.level}`;
106
+ }
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;
123
+ }
124
+ }
125
+ function composeOutputs(...outputs) {
126
+ return (entry) => {
127
+ outputs.forEach((output) => {
128
+ try {
129
+ output(entry);
130
+ } catch {
131
+ }
132
+ });
133
+ };
134
+ }
135
+
136
+ export {
137
+ parseLogLevel,
138
+ formatLogEntry,
139
+ createLogger,
140
+ createExtendedLogger,
141
+ consoleOutput,
142
+ composeOutputs
143
+ };
@@ -0,0 +1,17 @@
1
+ import { b as LogLevel, E as ExtendedLogger } from './core-BKAGZb-m.js';
2
+
3
+ /**
4
+ * @vllnt/logger — Convex-safe logger.
5
+ *
6
+ * Imports from core.ts (no process.env, no crypto).
7
+ * Works in Convex queries, mutations, and actions.
8
+ */
9
+
10
+ /**
11
+ * Create a logger for Convex functions.
12
+ * Pass level explicitly (Convex has no process.env in queries/mutations).
13
+ * Defaults to "info".
14
+ */
15
+ declare function createConvexLogger(scope: string, level?: LogLevel): ExtendedLogger;
16
+
17
+ export { createConvexLogger };
package/dist/convex.js ADDED
@@ -0,0 +1,15 @@
1
+ import {
2
+ consoleOutput,
3
+ createExtendedLogger
4
+ } from "./chunk-5GDAMA7T.js";
5
+
6
+ // src/convex.ts
7
+ function createConvexLogger(scope, level = "info") {
8
+ return createExtendedLogger(scope, {
9
+ getLogLevel: () => level,
10
+ output: consoleOutput
11
+ });
12
+ }
13
+ export {
14
+ createConvexLogger
15
+ };
@@ -0,0 +1,61 @@
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
+ /** Log levels ordered by severity */
8
+ type LogLevel = "debug" | "error" | "info" | "warn";
9
+ /** Structured log data payload */
10
+ type LogData = Record<string, unknown>;
11
+ /** Formatted log entry */
12
+ type LogEntry = {
13
+ event: string;
14
+ level: LogLevel;
15
+ timestamp: string;
16
+ } & Record<string, unknown>;
17
+ /** Logger interface — 4 level methods */
18
+ type Logger = {
19
+ debug: (event: string, data?: LogData) => void;
20
+ error: (event: string, data?: LogData) => void;
21
+ info: (event: string, data?: LogData) => void;
22
+ warn: (event: string, data?: LogData) => void;
23
+ };
24
+ /** Extended logger with timing helpers */
25
+ type ExtendedLogger = Logger & {
26
+ withTiming: <T>(label: string, execute: () => Promise<T>, extraData?: LogData) => Promise<T>;
27
+ withTimingSync: <T>(label: string, execute: () => T, extraData?: LogData) => T;
28
+ };
29
+ /** Output handler for log entries. Synchronous by design — async adapters must handle their own promises. */
30
+ type LogOutput = (entry: LogEntry) => void;
31
+ /** Configuration for creating a logger */
32
+ type LoggerConfig = {
33
+ /** Returns the current log level. Called on every log emit — keep it cheap. */
34
+ getLogLevel: () => LogLevel;
35
+ output: LogOutput;
36
+ };
37
+ /** Parse a log level string, returning default if invalid. */
38
+ declare function parseLogLevel(value: string | undefined, defaultLevel?: LogLevel): LogLevel;
39
+ /**
40
+ * Format a log entry. User data spread FIRST, fixed fields LAST.
41
+ * This prevents user data from overwriting event/level/timestamp.
42
+ */
43
+ declare function formatLogEntry(level: LogLevel, event: string, data?: LogData): LogEntry;
44
+ /** Create a scoped logger with the given configuration. */
45
+ declare function createLogger(scope: string, config: LoggerConfig): Logger;
46
+ /**
47
+ * Create an extended logger with timing helpers.
48
+ *
49
+ * @remarks Caught errors use `error.message` verbatim.
50
+ * Callers handling sensitive errors should sanitize before throwing.
51
+ */
52
+ declare function createExtendedLogger(scope: string, config: LoggerConfig): ExtendedLogger;
53
+ /**
54
+ * Default console output handler. Crash-safe — wraps JSON.stringify
55
+ * in try/catch to handle BigInt, circular refs, throwing toJSON.
56
+ */
57
+ declare function consoleOutput(entry: LogEntry): void;
58
+ /** Compose outputs into a single LogOutput. Each output runs in isolation. */
59
+ declare function composeOutputs(...outputs: LogOutput[]): LogOutput;
60
+
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 };
@@ -0,0 +1,14 @@
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';
3
+
4
+ /**
5
+ * @vllnt/logger — Backend preset.
6
+ *
7
+ * Pre-configured logger for Node.js backends.
8
+ * Reads LOG_LEVEL from process.env on each call (no module-level side effects).
9
+ */
10
+
11
+ /** Create a scoped backend logger. Reads LOG_LEVEL from process.env on each call. */
12
+ declare function createBackendLogger(scope: string): ExtendedLogger;
13
+
14
+ export { ExtendedLogger, createBackendLogger };
package/dist/index.js ADDED
@@ -0,0 +1,35 @@
1
+ import {
2
+ composeOutputs,
3
+ consoleOutput,
4
+ createExtendedLogger,
5
+ createLogger,
6
+ formatLogEntry,
7
+ parseLogLevel
8
+ } from "./chunk-5GDAMA7T.js";
9
+
10
+ // src/backend.ts
11
+ var HAS_PROCESS = typeof process !== "undefined";
12
+ function getEnvironmentVariable(key) {
13
+ if (HAS_PROCESS && process.env) {
14
+ return process.env[key];
15
+ }
16
+ return void 0;
17
+ }
18
+ function getBackendLogLevel() {
19
+ return parseLogLevel(getEnvironmentVariable("LOG_LEVEL"), "warn");
20
+ }
21
+ function createBackendLogger(scope) {
22
+ return createExtendedLogger(scope, {
23
+ getLogLevel: getBackendLogLevel,
24
+ output: consoleOutput
25
+ });
26
+ }
27
+ export {
28
+ composeOutputs,
29
+ consoleOutput,
30
+ createBackendLogger,
31
+ createExtendedLogger,
32
+ createLogger,
33
+ formatLogEntry,
34
+ parseLogLevel
35
+ };
@@ -0,0 +1,18 @@
1
+ import { c as LogOutput } from './core-BKAGZb-m.js';
2
+
3
+ /**
4
+ * @vllnt/logger — PostHog output adapter.
5
+ *
6
+ * Wraps a PostHog-style capture function as a LogOutput.
7
+ * No PostHog SDK dependency — consumer passes their own capture fn.
8
+ */
9
+
10
+ /** PostHog-compatible capture function signature */
11
+ type PostHogCapture = (event: string, properties?: Record<string, unknown>) => void;
12
+ /**
13
+ * Create a LogOutput that forwards entries to PostHog.
14
+ * Swallows errors from the capture function — logging must not break the app.
15
+ */
16
+ declare function createPostHogOutput(capture: PostHogCapture): LogOutput;
17
+
18
+ export { type PostHogCapture, createPostHogOutput };
@@ -0,0 +1,13 @@
1
+ // src/posthog.ts
2
+ function createPostHogOutput(capture) {
3
+ return (entry) => {
4
+ try {
5
+ const { event, ...properties } = entry;
6
+ capture(event, properties);
7
+ } catch {
8
+ }
9
+ };
10
+ }
11
+ export {
12
+ createPostHogOutput
13
+ };
@@ -0,0 +1,17 @@
1
+ import { a as LogEntry, c as LogOutput } from './core-BKAGZb-m.js';
2
+
3
+ /**
4
+ * @vllnt/logger — Test utilities.
5
+ *
6
+ * Provides a test output that captures log entries for assertion.
7
+ */
8
+
9
+ /** Result of createTestOutput — output function + captured entries */
10
+ type TestOutput = {
11
+ entries: readonly LogEntry[];
12
+ output: LogOutput;
13
+ };
14
+ /** Create a test output that captures entries into an array for assertion. */
15
+ declare function createTestOutput(): TestOutput;
16
+
17
+ export { type TestOutput, createTestOutput };
@@ -0,0 +1,11 @@
1
+ // src/testing.ts
2
+ function createTestOutput() {
3
+ const entries = [];
4
+ const output = (entry) => {
5
+ entries.push(entry);
6
+ };
7
+ return { entries, output };
8
+ }
9
+ export {
10
+ createTestOutput
11
+ };
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@vllnt/logger",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "Structured logging for the @vllnt ecosystem",
6
+ "license": "MIT",
7
+ "author": "bntvllnt",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/vllnt/logger"
11
+ },
12
+ "sideEffects": false,
13
+ "exports": {
14
+ ".": {
15
+ "import": "./dist/index.js",
16
+ "types": "./dist/index.d.ts"
17
+ },
18
+ "./convex": {
19
+ "import": "./dist/convex.js",
20
+ "types": "./dist/convex.d.ts"
21
+ },
22
+ "./posthog": {
23
+ "import": "./dist/posthog.js",
24
+ "types": "./dist/posthog.d.ts"
25
+ },
26
+ "./testing": {
27
+ "import": "./dist/testing.js",
28
+ "types": "./dist/testing.d.ts"
29
+ }
30
+ },
31
+ "files": [
32
+ "dist"
33
+ ],
34
+ "publishConfig": {
35
+ "access": "public",
36
+ "registry": "https://registry.npmjs.org/"
37
+ },
38
+ "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"
47
+ },
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"
55
+ }
56
+ }