logosaur 0.1.1 → 0.2.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/README.md CHANGED
@@ -18,10 +18,15 @@ else dragged into your `node_modules`. Rawr.
18
18
  bun add logosaur
19
19
  ```
20
20
 
21
- It works in Node too: `npm install logosaur`.
21
+ It works in Node and Deno too:
22
+
23
+ ```bash
24
+ npm install logosaur
25
+ deno add jsr:@0c71/logosaur
26
+ ```
22
27
 
23
28
  That's the whole install. logosaur has **zero dependencies**, so it's one small
24
- package (about 5 kB) and nothing else: no tree of transitive installs, nothing
29
+ package (about 8 kB) and nothing else: no tree of transitive installs, nothing
25
30
  to audit but the one file. 🦴
26
31
 
27
32
  ## How it compares
@@ -29,7 +34,7 @@ to audit but the one file. 🦴
29
34
  | | logosaur | pino | winston | tslog | consola |
30
35
  | --------------------- | --------- | -------- | -------- | -------- | -------- |
31
36
  | Packages installed | **1** | 13 | 28 | 1 | 1 |
32
- | Install size | **14 kB** | 1.2 MB | 1.9 MB | 980 kB | 310 kB |
37
+ | Install size | **19 kB** | 1.2 MB | 1.9 MB | 980 kB | 310 kB |
33
38
  | Import, Node / Bun | **4 / 6 ms** | 18 / 18 ms | 31 / 29 ms | 20 / 12 ms | 14 / 10 ms |
34
39
  | JSON lines/s, Node / Bun | 1.1M / **2.6M** | **2.7M / 2.6M** | 290k / 530k | 550k / 700k | |
35
40
  | Text lines/s, Node / Bun | **830k / 1.2M** | | | 280k / 320k | 100k / 120k |
@@ -113,6 +118,33 @@ cave.info("echo");
113
118
  // 14:02:03 INF cave: echo
114
119
  ```
115
120
 
121
+ ## Request logging
122
+
123
+ One line per request, for [Hono](https://hono.dev) and
124
+ [Elysia](https://elysiajs.com): info, warn for a 4xx, error for a 5xx.
125
+
126
+ ```ts
127
+ import { Hono } from "hono";
128
+ import { logosaur } from "logosaur/hono";
129
+
130
+ const app = new Hono().use(logosaur());
131
+ ```
132
+
133
+ ```ts
134
+ import { Elysia } from "elysia";
135
+ import { logosaur } from "logosaur/elysia";
136
+
137
+ const app = new Elysia().use(logosaur());
138
+ ```
139
+
140
+ ```
141
+ 14:02:03 INF request method=GET path=/eggs status=200 ms=1.2
142
+ 14:02:04 WRN request method=POST path=/nope status=404 ms=0.3
143
+ ```
144
+
145
+ Pass your own logger to set its level, format or fields:
146
+ `logosaur(log.with({ service: "park" }))`.
147
+
116
148
  ## Options
117
149
 
118
150
  ```ts
@@ -0,0 +1,4 @@
1
+ import { Elysia } from "elysia";
2
+ import { type Logger } from "./index.ts";
3
+ declare const logosaur: (log?: Logger) => Elysia;
4
+ export { logosaur };
package/dist/elysia.js ADDED
@@ -0,0 +1,26 @@
1
+ import {
2
+ log2
3
+ } from "./index-7aws7kd9.js";
4
+ import {
5
+ logRequest
6
+ } from "./index-ccp2zts5.js";
7
+
8
+ // src/elysia.ts
9
+ import { Elysia, StatusMap } from "elysia";
10
+ var toCode = (status) => {
11
+ if (typeof status === "number")
12
+ return status;
13
+ return StatusMap[status] ?? 200;
14
+ };
15
+ var logosaur = (log = log2) => {
16
+ const starts = new WeakMap;
17
+ return new Elysia({ name: "logosaur", seed: log }).onRequest(({ request }) => {
18
+ starts.set(request, performance.now());
19
+ }).onAfterResponse({ as: "global" }, ({ request, path, set }) => {
20
+ const start = starts.get(request) ?? performance.now();
21
+ logRequest(log, request.method, path, toCode(set.status), start);
22
+ });
23
+ };
24
+ export {
25
+ logosaur
26
+ };
package/dist/hono.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import type { MiddlewareHandler } from "hono";
2
+ import { type Logger } from "./index.ts";
3
+ declare const logosaur: (log?: Logger) => MiddlewareHandler;
4
+ export { logosaur };
package/dist/hono.js ADDED
@@ -0,0 +1,16 @@
1
+ import {
2
+ log2
3
+ } from "./index-7aws7kd9.js";
4
+ import {
5
+ logRequest
6
+ } from "./index-ccp2zts5.js";
7
+
8
+ // src/hono.ts
9
+ var logosaur = (log = log2) => async (c, next) => {
10
+ const start = performance.now();
11
+ await next();
12
+ logRequest(log, c.req.method, c.req.path, c.res.status, start);
13
+ };
14
+ export {
15
+ logosaur
16
+ };
@@ -0,0 +1,216 @@
1
+ // src/index.ts
2
+ import { appendFileSync, mkdirSync } from "node:fs";
3
+ import { dirname } from "node:path";
4
+ var levels = {
5
+ debug: { rank: 0, label: "DBG", color: 63 },
6
+ info: { rank: 1, label: "INF", color: 86 },
7
+ warn: { rank: 2, label: "WRN", color: 192 },
8
+ error: { rank: 3, label: "ERR", color: 204 },
9
+ fatal: { rank: 4, label: "FTL", color: 134 }
10
+ };
11
+ var bold = "\x1B[1m";
12
+ var faint = "\x1B[2m";
13
+ var reset = "\x1B[0m";
14
+ var fg = (code) => `\x1B[38;5;${code}m`;
15
+ var paint = (on, text, ...styles) => on ? `${styles.join("")}${text}${reset}` : text;
16
+ var supportsColor = (output) => {
17
+ const { NO_COLOR, FORCE_COLOR } = process.env;
18
+ if (NO_COLOR)
19
+ return false;
20
+ if (FORCE_COLOR)
21
+ return FORCE_COLOR !== "0" && FORCE_COLOR !== "false";
22
+ return output.isTTY === true;
23
+ };
24
+ var normalize = (value) => {
25
+ if (value instanceof Error)
26
+ return value.message;
27
+ if (value instanceof Date)
28
+ return value.toISOString();
29
+ if (typeof value === "bigint")
30
+ return value.toString();
31
+ return value;
32
+ };
33
+ var shaper = (replacer) => (key, value) => normalize(replacer ? replacer(key, value) : value);
34
+ var formatValue2 = (value) => {
35
+ if (value === null || value === undefined)
36
+ return "<nil>";
37
+ if (Array.isArray(value))
38
+ return `[${value.map(formatValue2).join(" ")}]`;
39
+ if (typeof value === "string") {
40
+ return value === "" || /[\s="]/.test(value) ? JSON.stringify(value) : value;
41
+ }
42
+ if (typeof value === "object") {
43
+ try {
44
+ return JSON.stringify(value);
45
+ } catch {
46
+ return "[unserializable]";
47
+ }
48
+ }
49
+ return String(value);
50
+ };
51
+ var plain = (value, depth = 0) => {
52
+ if (typeof value === "bigint")
53
+ return false;
54
+ if (typeof value !== "object" || value === null)
55
+ return true;
56
+ if (value instanceof Error || depth > 8)
57
+ return false;
58
+ for (const item of Object.values(value)) {
59
+ if (!plain(item, depth + 1))
60
+ return false;
61
+ }
62
+ return true;
63
+ };
64
+ var pairs2 = (fields, replacer) => {
65
+ const shape = shaper(replacer);
66
+ const out = [];
67
+ const parents = new Set;
68
+ const walk = (node, path) => {
69
+ parents.add(node);
70
+ for (const [key, raw] of Object.entries(node)) {
71
+ const value = shape(key, raw);
72
+ const name = `${path}${key}`;
73
+ if (value == null)
74
+ continue;
75
+ if (Array.isArray(value)) {
76
+ out.push([name, value.filter((v) => v != null).map(normalize)]);
77
+ } else if (typeof value !== "object") {
78
+ out.push([name, value]);
79
+ } else if (parents.has(value)) {
80
+ out.push([name, "[circular]"]);
81
+ } else {
82
+ walk(value, `${name}.`);
83
+ }
84
+ }
85
+ parents.delete(node);
86
+ };
87
+ walk(fields, "");
88
+ return out;
89
+ };
90
+ var makeClock = (timeZone) => {
91
+ let format;
92
+ let second = Number.NaN;
93
+ let last = { day: "", time: "" };
94
+ return (date) => {
95
+ const now = Math.floor(date.getTime() / 1000);
96
+ if (now === second)
97
+ return last;
98
+ format ??= new Intl.DateTimeFormat("en-US", {
99
+ timeZone,
100
+ hourCycle: "h23",
101
+ year: "numeric",
102
+ month: "2-digit",
103
+ day: "2-digit",
104
+ hour: "2-digit",
105
+ minute: "2-digit",
106
+ second: "2-digit"
107
+ });
108
+ const p = Object.fromEntries(format.formatToParts(date).map(({ type, value }) => [type, value]));
109
+ second = now;
110
+ last = {
111
+ day: `${p.year}-${p.month}-${p.day}`,
112
+ time: `${p.hour}:${p.minute}:${p.second}`
113
+ };
114
+ return last;
115
+ };
116
+ };
117
+ var createLogger2 = (options = {}) => {
118
+ const {
119
+ prefix,
120
+ fields = {},
121
+ time = true,
122
+ timeZone,
123
+ format = "text",
124
+ output = process.stderr,
125
+ file,
126
+ replacer,
127
+ now = () => new Date
128
+ } = options;
129
+ let threshold = options.level ?? "info";
130
+ const color = options.color ?? supportsColor(output);
131
+ const clock = makeClock(timeZone);
132
+ const shape = shaper(replacer);
133
+ const madeDirs = new Set;
134
+ const toJson = (meta, merged) => {
135
+ const line = { ...meta, ...merged };
136
+ if (!replacer && plain(merged))
137
+ return JSON.stringify(line);
138
+ try {
139
+ return JSON.stringify(line, function(key, value) {
140
+ const own = key === "" || this === line && Object.hasOwn(meta, key) && !Object.hasOwn(merged, key);
141
+ return own ? value : shape(key, value);
142
+ });
143
+ } catch {
144
+ return JSON.stringify({
145
+ ...meta,
146
+ ...Object.fromEntries(pairs2(merged, replacer))
147
+ });
148
+ }
149
+ };
150
+ const render = (level, msg, extra, date, colored) => {
151
+ const merged = { ...fields, ...extra };
152
+ const meta = {
153
+ time: date.toISOString(),
154
+ level,
155
+ ...prefix ? { prefix } : {},
156
+ msg
157
+ };
158
+ if (format === "json") {
159
+ return toJson(meta, merged);
160
+ }
161
+ const context = pairs2(merged, replacer);
162
+ if (format === "logfmt") {
163
+ return [...Object.entries(meta), ...context].map(([key, value]) => `${key}=${formatValue2(value)}`).join(" ");
164
+ }
165
+ const { label, color: code } = levels[level];
166
+ return [
167
+ time && clock(date).time,
168
+ paint(colored, label, bold, fg(code)),
169
+ prefix && paint(colored, `${prefix}:`, bold),
170
+ msg,
171
+ ...context.map(([key, value]) => `${paint(colored, key, faint)}=${formatValue2(value)}`)
172
+ ].filter(Boolean).join(" ");
173
+ };
174
+ const append = (path, line) => {
175
+ const dir = dirname(path);
176
+ if (!madeDirs.has(dir)) {
177
+ mkdirSync(dir, { recursive: true });
178
+ madeDirs.add(dir);
179
+ }
180
+ appendFileSync(path, `${line}
181
+ `);
182
+ };
183
+ const write = (level, msg, extra) => {
184
+ if (levels[level].rank < levels[threshold].rank)
185
+ return;
186
+ const date = now();
187
+ output.write(`${render(level, msg, extra, date, color)}
188
+ `);
189
+ if (file) {
190
+ const path = typeof file === "function" ? file(clock(date).day) : file;
191
+ append(path, render(level, msg, extra, date, false));
192
+ }
193
+ };
194
+ const at = (level) => (msg, extra) => write(level, msg, extra);
195
+ const child = (overrides) => createLogger2({ ...options, level: threshold, ...overrides });
196
+ return {
197
+ debug: at("debug"),
198
+ info: at("info"),
199
+ warn: at("warn"),
200
+ error: at("error"),
201
+ fatal: (msg, extra) => {
202
+ write("fatal", msg, extra);
203
+ return process.exit(1);
204
+ },
205
+ with: (more) => child({ fields: { ...fields, ...more } }),
206
+ withPrefix: (next) => child({ prefix: next }),
207
+ setLevel: (level) => {
208
+ threshold = level;
209
+ },
210
+ get level() {
211
+ return threshold;
212
+ }
213
+ };
214
+ };
215
+ var log2 = createLogger2();
216
+ export { formatValue2, pairs2, createLogger2, log2 };
@@ -0,0 +1,8 @@
1
+ // src/request.ts
2
+ var logRequest = (log, method, path, status, start) => {
3
+ const ms = Math.round((performance.now() - start) * 10) / 10;
4
+ const level = status >= 500 ? "error" : status >= 400 ? "warn" : "info";
5
+ log[level]("request", { method, path, status, ms });
6
+ };
7
+
8
+ export { logRequest };
package/dist/index.js CHANGED
@@ -1,221 +1,12 @@
1
- // src/index.ts
2
- import { appendFileSync, mkdirSync } from "node:fs";
3
- import { dirname } from "node:path";
4
- var levels = {
5
- debug: { rank: 0, label: "DBG", color: 63 },
6
- info: { rank: 1, label: "INF", color: 86 },
7
- warn: { rank: 2, label: "WRN", color: 192 },
8
- error: { rank: 3, label: "ERR", color: 204 },
9
- fatal: { rank: 4, label: "FTL", color: 134 }
10
- };
11
- var bold = "\x1B[1m";
12
- var faint = "\x1B[2m";
13
- var reset = "\x1B[0m";
14
- var fg = (code) => `\x1B[38;5;${code}m`;
15
- var paint = (on, text, ...styles) => on ? `${styles.join("")}${text}${reset}` : text;
16
- var supportsColor = (output) => {
17
- const { NO_COLOR, FORCE_COLOR } = process.env;
18
- if (NO_COLOR)
19
- return false;
20
- if (FORCE_COLOR)
21
- return FORCE_COLOR !== "0" && FORCE_COLOR !== "false";
22
- return output.isTTY === true;
23
- };
24
- var normalize = (value) => {
25
- if (value instanceof Error)
26
- return value.message;
27
- if (value instanceof Date)
28
- return value.toISOString();
29
- if (typeof value === "bigint")
30
- return value.toString();
31
- return value;
32
- };
33
- var shaper = (replacer) => (key, value) => normalize(replacer ? replacer(key, value) : value);
34
- var formatValue = (value) => {
35
- if (value === null || value === undefined)
36
- return "<nil>";
37
- if (Array.isArray(value))
38
- return `[${value.map(formatValue).join(" ")}]`;
39
- if (typeof value === "string") {
40
- return value === "" || /[\s="]/.test(value) ? JSON.stringify(value) : value;
41
- }
42
- if (typeof value === "object") {
43
- try {
44
- return JSON.stringify(value);
45
- } catch {
46
- return "[unserializable]";
47
- }
48
- }
49
- return String(value);
50
- };
51
- var plain = (value, depth = 0) => {
52
- if (typeof value === "bigint")
53
- return false;
54
- if (typeof value !== "object" || value === null)
55
- return true;
56
- if (value instanceof Error || depth > 8)
57
- return false;
58
- for (const item of Object.values(value)) {
59
- if (!plain(item, depth + 1))
60
- return false;
61
- }
62
- return true;
63
- };
64
- var pairs = (fields, replacer) => {
65
- const shape = shaper(replacer);
66
- const out = [];
67
- const parents = new Set;
68
- const walk = (node, path) => {
69
- parents.add(node);
70
- for (const [key, raw] of Object.entries(node)) {
71
- const value = shape(key, raw);
72
- const name = `${path}${key}`;
73
- if (value == null)
74
- continue;
75
- if (Array.isArray(value)) {
76
- out.push([name, value.filter((v) => v != null).map(normalize)]);
77
- } else if (typeof value !== "object") {
78
- out.push([name, value]);
79
- } else if (parents.has(value)) {
80
- out.push([name, "[circular]"]);
81
- } else {
82
- walk(value, `${name}.`);
83
- }
84
- }
85
- parents.delete(node);
86
- };
87
- walk(fields, "");
88
- return out;
89
- };
90
- var makeClock = (timeZone) => {
91
- let format;
92
- let second = Number.NaN;
93
- let last = { day: "", time: "" };
94
- return (date) => {
95
- const now = Math.floor(date.getTime() / 1000);
96
- if (now === second)
97
- return last;
98
- format ??= new Intl.DateTimeFormat("en-US", {
99
- timeZone,
100
- hourCycle: "h23",
101
- year: "numeric",
102
- month: "2-digit",
103
- day: "2-digit",
104
- hour: "2-digit",
105
- minute: "2-digit",
106
- second: "2-digit"
107
- });
108
- const p = Object.fromEntries(format.formatToParts(date).map(({ type, value }) => [type, value]));
109
- second = now;
110
- last = {
111
- day: `${p.year}-${p.month}-${p.day}`,
112
- time: `${p.hour}:${p.minute}:${p.second}`
113
- };
114
- return last;
115
- };
116
- };
117
- var createLogger = (options = {}) => {
118
- const {
119
- prefix,
120
- fields = {},
121
- time = true,
122
- timeZone,
123
- format = "text",
124
- output = process.stderr,
125
- file,
126
- replacer,
127
- now = () => new Date
128
- } = options;
129
- let threshold = options.level ?? "info";
130
- const color = options.color ?? supportsColor(output);
131
- const clock = makeClock(timeZone);
132
- const shape = shaper(replacer);
133
- const madeDirs = new Set;
134
- const toJson = (meta, merged) => {
135
- const line = { ...meta, ...merged };
136
- if (!replacer && plain(merged))
137
- return JSON.stringify(line);
138
- try {
139
- return JSON.stringify(line, function(key, value) {
140
- const own = key === "" || this === line && Object.hasOwn(meta, key) && !Object.hasOwn(merged, key);
141
- return own ? value : shape(key, value);
142
- });
143
- } catch {
144
- return JSON.stringify({
145
- ...meta,
146
- ...Object.fromEntries(pairs(merged, replacer))
147
- });
148
- }
149
- };
150
- const render = (level, msg, extra, date, colored) => {
151
- const merged = { ...fields, ...extra };
152
- const meta = {
153
- time: date.toISOString(),
154
- level,
155
- ...prefix ? { prefix } : {},
156
- msg
157
- };
158
- if (format === "json") {
159
- return toJson(meta, merged);
160
- }
161
- const context = pairs(merged, replacer);
162
- if (format === "logfmt") {
163
- return [...Object.entries(meta), ...context].map(([key, value]) => `${key}=${formatValue(value)}`).join(" ");
164
- }
165
- const { label, color: code } = levels[level];
166
- return [
167
- time && clock(date).time,
168
- paint(colored, label, bold, fg(code)),
169
- prefix && paint(colored, `${prefix}:`, bold),
170
- msg,
171
- ...context.map(([key, value]) => `${paint(colored, key, faint)}=${formatValue(value)}`)
172
- ].filter(Boolean).join(" ");
173
- };
174
- const append = (path, line) => {
175
- const dir = dirname(path);
176
- if (!madeDirs.has(dir)) {
177
- mkdirSync(dir, { recursive: true });
178
- madeDirs.add(dir);
179
- }
180
- appendFileSync(path, `${line}
181
- `);
182
- };
183
- const write = (level, msg, extra) => {
184
- if (levels[level].rank < levels[threshold].rank)
185
- return;
186
- const date = now();
187
- output.write(`${render(level, msg, extra, date, color)}
188
- `);
189
- if (file) {
190
- const path = typeof file === "function" ? file(clock(date).day) : file;
191
- append(path, render(level, msg, extra, date, false));
192
- }
193
- };
194
- const at = (level) => (msg, extra) => write(level, msg, extra);
195
- const child = (overrides) => createLogger({ ...options, level: threshold, ...overrides });
196
- return {
197
- debug: at("debug"),
198
- info: at("info"),
199
- warn: at("warn"),
200
- error: at("error"),
201
- fatal: (msg, extra) => {
202
- write("fatal", msg, extra);
203
- return process.exit(1);
204
- },
205
- with: (more) => child({ fields: { ...fields, ...more } }),
206
- withPrefix: (next) => child({ prefix: next }),
207
- setLevel: (level) => {
208
- threshold = level;
209
- },
210
- get level() {
211
- return threshold;
212
- }
213
- };
214
- };
215
- var log = createLogger();
1
+ import {
2
+ formatValue2,
3
+ pairs2,
4
+ createLogger2,
5
+ log2
6
+ } from "./index-7aws7kd9.js";
216
7
  export {
217
- createLogger,
218
- formatValue,
219
- log,
220
- pairs
8
+ createLogger2 as createLogger,
9
+ formatValue2 as formatValue,
10
+ log2 as log,
11
+ pairs2 as pairs
221
12
  };
@@ -0,0 +1,3 @@
1
+ import type { Logger } from "./index.ts";
2
+ declare const logRequest: (log: Logger, method: string, path: string, status: number, start: number) => void;
3
+ export { logRequest };
package/package.json CHANGED
@@ -1,16 +1,29 @@
1
1
  {
2
2
  "name": "logosaur",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "A tiny, colorful, zero-dependency structured logger for Bun and TypeScript. Rawr.",
5
5
  "keywords": [
6
6
  "log",
7
7
  "logger",
8
8
  "logging",
9
9
  "structured",
10
+ "structured-logging",
11
+ "json",
10
12
  "logfmt",
11
13
  "bun",
14
+ "deno",
15
+ "node",
12
16
  "typescript",
13
- "color"
17
+ "color",
18
+ "tiny",
19
+ "fast",
20
+ "lightweight",
21
+ "zero-dependency",
22
+ "hono",
23
+ "elysia",
24
+ "middleware",
25
+ "pino-alternative",
26
+ "consola-alternative"
14
27
  ],
15
28
  "license": "MIT",
16
29
  "repository": {
@@ -26,6 +39,14 @@
26
39
  ".": {
27
40
  "types": "./dist/index.d.ts",
28
41
  "import": "./dist/index.js"
42
+ },
43
+ "./hono": {
44
+ "types": "./dist/hono.d.ts",
45
+ "import": "./dist/hono.js"
46
+ },
47
+ "./elysia": {
48
+ "types": "./dist/elysia.d.ts",
49
+ "import": "./dist/elysia.js"
29
50
  }
30
51
  },
31
52
  "files": [
@@ -33,13 +54,27 @@
33
54
  ],
34
55
  "sideEffects": false,
35
56
  "scripts": {
36
- "build": "bun build src/index.ts --outdir dist --target node && tsc -p tsconfig.build.json",
57
+ "build": "bun build src/index.ts src/hono.ts src/elysia.ts --outdir dist --target node --splitting --packages external && tsc -p tsconfig.build.json",
37
58
  "test": "bun test",
38
59
  "typecheck": "tsc --noEmit",
39
60
  "prepublishOnly": "bun run typecheck && bun test && bun run build"
40
61
  },
62
+ "peerDependencies": {
63
+ "elysia": ">=1.1",
64
+ "hono": ">=4"
65
+ },
66
+ "peerDependenciesMeta": {
67
+ "elysia": {
68
+ "optional": true
69
+ },
70
+ "hono": {
71
+ "optional": true
72
+ }
73
+ },
41
74
  "devDependencies": {
42
75
  "@types/bun": "^1.4.4",
76
+ "elysia": "^1.4.32",
77
+ "hono": "^4.13.23",
43
78
  "typescript": "^7.0.2"
44
79
  }
45
80
  }