@logtape/elysia 1.4.0-dev.1

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,20 @@
1
+ MIT License
2
+
3
+ Copyright 2024–2025 Hong Minhee
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ 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, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,140 @@
1
+ <!-- deno-fmt-ignore-file -->
2
+
3
+ @logtape/elysia
4
+ ===============
5
+
6
+ [![JSR][JSR badge]][JSR]
7
+ [![npm][npm badge]][npm]
8
+
9
+ This package provides an [Elysia] plugin for HTTP request logging using
10
+ [LogTape] as the backend.
11
+
12
+ [JSR]: https://jsr.io/@logtape/elysia
13
+ [JSR badge]: https://jsr.io/badges/@logtape/elysia
14
+ [npm]: https://www.npmjs.com/package/@logtape/elysia
15
+ [npm badge]: https://img.shields.io/npm/v/@logtape/elysia?logo=npm
16
+ [Elysia]: https://elysiajs.com/
17
+ [LogTape]: https://logtape.org/
18
+
19
+
20
+ Installation
21
+ ------------
22
+
23
+ ~~~~ sh
24
+ deno add jsr:@logtape/elysia # for Deno
25
+ npm add @logtape/elysia # for npm
26
+ pnpm add @logtape/elysia # for pnpm
27
+ yarn add @logtape/elysia # for Yarn
28
+ bun add @logtape/elysia # for Bun
29
+ ~~~~
30
+
31
+
32
+ Usage
33
+ -----
34
+
35
+ ~~~~ typescript
36
+ import { Elysia } from "elysia";
37
+ import { configure, getConsoleSink } from "@logtape/logtape";
38
+ import { elysiaLogger } from "@logtape/elysia";
39
+
40
+ await configure({
41
+ sinks: { console: getConsoleSink() },
42
+ loggers: [
43
+ { category: ["elysia"], sinks: ["console"], lowestLevel: "info" }
44
+ ],
45
+ });
46
+
47
+ const app = new Elysia()
48
+ .use(elysiaLogger())
49
+ .get("/", () => ({ hello: "world" }))
50
+ .listen(3000);
51
+
52
+ console.log(`Server running at ${app.server?.url}`);
53
+ ~~~~
54
+
55
+
56
+ Options
57
+ -------
58
+
59
+ The `elysiaLogger()` function accepts an optional options object:
60
+
61
+ ~~~~ typescript
62
+ app.use(elysiaLogger({
63
+ category: ["myapp", "http"], // Custom category (default: ["elysia"])
64
+ level: "debug", // Log level (default: "info")
65
+ format: "dev", // Predefined format (default: "combined")
66
+ skip: (ctx) => ctx.path === "/health", // Skip logging for specific paths
67
+ logRequest: true, // Log at request start (default: false)
68
+ scope: "global", // Plugin scope (default: "global")
69
+ }));
70
+ ~~~~
71
+
72
+
73
+ Plugin scope
74
+ ------------
75
+
76
+ Elysia supports plugin scoping to control how lifecycle hooks propagate:
77
+
78
+ - `"global"`: Hooks apply to all routes in the application (default)
79
+ - `"scoped"`: Hooks apply to the parent instance where the plugin is used
80
+ - `"local"`: Hooks only apply within the plugin itself
81
+
82
+
83
+ Predefined formats
84
+ ------------------
85
+
86
+ The plugin supports Morgan-compatible predefined formats:
87
+
88
+ - `"combined"`: Apache Combined Log Format with all properties (default)
89
+ - `"common"`: Apache Common Log Format (without referrer/userAgent)
90
+ - `"dev"`: Concise output for development (e.g., `GET /path 200 1.234 ms - 123`)
91
+ - `"short"`: Shorter format with remote address
92
+ - `"tiny"`: Minimal output
93
+
94
+
95
+ Custom format function
96
+ ----------------------
97
+
98
+ You can also provide a custom format function:
99
+
100
+ ~~~~ typescript
101
+ app.use(elysiaLogger({
102
+ format: (ctx, responseTime) => ({
103
+ method: ctx.request.method,
104
+ path: ctx.path,
105
+ status: ctx.set.status,
106
+ duration: responseTime,
107
+ }),
108
+ }));
109
+ ~~~~
110
+
111
+
112
+ Error logging
113
+ -------------
114
+
115
+ The plugin automatically logs errors at the error level using Elysia's
116
+ `onError` hook. Error logs include the error message and error code
117
+ in addition to standard request properties.
118
+
119
+
120
+ Structured logging output
121
+ -------------------------
122
+
123
+ When using the `"combined"` format (default), the plugin logs structured
124
+ data that includes:
125
+
126
+ - `method`: HTTP request method
127
+ - `url`: Request URL
128
+ - `path`: Request path
129
+ - `status`: HTTP response status code
130
+ - `responseTime`: Response time in milliseconds
131
+ - `contentLength`: Response content-length header value
132
+ - `remoteAddr`: Remote client address (from X-Forwarded-For header)
133
+ - `userAgent`: User-Agent header value
134
+ - `referrer`: Referrer header value
135
+
136
+
137
+ See also
138
+ --------
139
+
140
+ For more information, see the [LogTape documentation][LogTape].
@@ -0,0 +1,30 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+
23
+ //#endregion
24
+
25
+ Object.defineProperty(exports, '__toESM', {
26
+ enumerable: true,
27
+ get: function () {
28
+ return __toESM;
29
+ }
30
+ });
package/dist/mod.cjs ADDED
@@ -0,0 +1,214 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ const elysia = require_rolldown_runtime.__toESM(require("elysia"));
3
+ const __logtape_logtape = require_rolldown_runtime.__toESM(require("@logtape/logtape"));
4
+
5
+ //#region src/mod.ts
6
+ /**
7
+ * Get referrer from request headers.
8
+ */
9
+ function getReferrer(request) {
10
+ return request.headers.get("referrer") ?? request.headers.get("referer") ?? void 0;
11
+ }
12
+ /**
13
+ * Get user agent from request headers.
14
+ */
15
+ function getUserAgent(request) {
16
+ return request.headers.get("user-agent") ?? void 0;
17
+ }
18
+ /**
19
+ * Get remote address from X-Forwarded-For header.
20
+ */
21
+ function getRemoteAddr(request) {
22
+ const forwarded = request.headers.get("x-forwarded-for");
23
+ if (forwarded) {
24
+ const firstIp = forwarded.split(",")[0].trim();
25
+ return firstIp || void 0;
26
+ }
27
+ return void 0;
28
+ }
29
+ /**
30
+ * Get content length from response headers.
31
+ */
32
+ function getContentLength(headers) {
33
+ const contentLength = headers["content-length"];
34
+ if (contentLength === void 0 || contentLength === null) return void 0;
35
+ return contentLength;
36
+ }
37
+ /**
38
+ * Build structured log properties from context.
39
+ */
40
+ function buildProperties(ctx, responseTime) {
41
+ return {
42
+ method: ctx.request.method,
43
+ url: ctx.request.url,
44
+ path: ctx.path,
45
+ status: ctx.set.status,
46
+ responseTime,
47
+ contentLength: getContentLength(ctx.set.headers),
48
+ remoteAddr: getRemoteAddr(ctx.request),
49
+ userAgent: getUserAgent(ctx.request),
50
+ referrer: getReferrer(ctx.request)
51
+ };
52
+ }
53
+ /**
54
+ * Combined format (Apache Combined Log Format).
55
+ * Returns all structured properties.
56
+ */
57
+ function formatCombined(ctx, responseTime) {
58
+ return { ...buildProperties(ctx, responseTime) };
59
+ }
60
+ /**
61
+ * Common format (Apache Common Log Format).
62
+ * Like combined but without referrer and userAgent.
63
+ */
64
+ function formatCommon(ctx, responseTime) {
65
+ const props = buildProperties(ctx, responseTime);
66
+ const { referrer: _referrer, userAgent: _userAgent,...rest } = props;
67
+ return rest;
68
+ }
69
+ /**
70
+ * Dev format (colored output for development).
71
+ * :method :path :status :response-time ms - :res[content-length]
72
+ */
73
+ function formatDev(ctx, responseTime) {
74
+ const contentLength = getContentLength(ctx.set.headers) ?? "-";
75
+ return `${ctx.request.method} ${ctx.path} ${ctx.set.status} ${responseTime.toFixed(3)} ms - ${contentLength}`;
76
+ }
77
+ /**
78
+ * Short format.
79
+ * :remote-addr :method :url :status :res[content-length] - :response-time ms
80
+ */
81
+ function formatShort(ctx, responseTime) {
82
+ const remoteAddr = getRemoteAddr(ctx.request) ?? "-";
83
+ const contentLength = getContentLength(ctx.set.headers) ?? "-";
84
+ return `${remoteAddr} ${ctx.request.method} ${ctx.request.url} ${ctx.set.status} ${contentLength} - ${responseTime.toFixed(3)} ms`;
85
+ }
86
+ /**
87
+ * Tiny format (minimal output).
88
+ * :method :path :status :res[content-length] - :response-time ms
89
+ */
90
+ function formatTiny(ctx, responseTime) {
91
+ const contentLength = getContentLength(ctx.set.headers) ?? "-";
92
+ return `${ctx.request.method} ${ctx.path} ${ctx.set.status} ${contentLength} - ${responseTime.toFixed(3)} ms`;
93
+ }
94
+ /**
95
+ * Map of predefined format functions.
96
+ */
97
+ const predefinedFormats = {
98
+ combined: formatCombined,
99
+ common: formatCommon,
100
+ dev: formatDev,
101
+ short: formatShort,
102
+ tiny: formatTiny
103
+ };
104
+ /**
105
+ * Normalize category to array format.
106
+ */
107
+ function normalizeCategory(category) {
108
+ return typeof category === "string" ? [category] : category;
109
+ }
110
+ /**
111
+ * Creates Elysia plugin for HTTP request logging using LogTape.
112
+ *
113
+ * This plugin provides Morgan-compatible request logging with LogTape
114
+ * as the backend, supporting structured logging and customizable formats.
115
+ *
116
+ * @example Basic usage
117
+ * ```typescript
118
+ * import { Elysia } from "elysia";
119
+ * import { configure, getConsoleSink } from "@logtape/logtape";
120
+ * import { elysiaLogger } from "@logtape/elysia";
121
+ *
122
+ * await configure({
123
+ * sinks: { console: getConsoleSink() },
124
+ * loggers: [
125
+ * { category: ["elysia"], sinks: ["console"], lowestLevel: "info" }
126
+ * ],
127
+ * });
128
+ *
129
+ * const app = new Elysia()
130
+ * .use(elysiaLogger())
131
+ * .get("/", () => ({ hello: "world" }))
132
+ * .listen(3000);
133
+ * ```
134
+ *
135
+ * @example With custom options
136
+ * ```typescript
137
+ * app.use(elysiaLogger({
138
+ * category: ["myapp", "http"],
139
+ * level: "debug",
140
+ * format: "dev",
141
+ * skip: (ctx) => ctx.path === "/health",
142
+ * scope: "scoped",
143
+ * }));
144
+ * ```
145
+ *
146
+ * @example With custom format function
147
+ * ```typescript
148
+ * app.use(elysiaLogger({
149
+ * format: (ctx, responseTime) => ({
150
+ * method: ctx.request.method,
151
+ * path: ctx.path,
152
+ * status: ctx.set.status,
153
+ * duration: responseTime,
154
+ * }),
155
+ * }));
156
+ * ```
157
+ *
158
+ * @param options Configuration options for the plugin.
159
+ * @returns Elysia plugin instance.
160
+ * @since 1.4.0
161
+ */
162
+ function elysiaLogger(options = {}) {
163
+ const category = normalizeCategory(options.category ?? ["elysia"]);
164
+ const logger = (0, __logtape_logtape.getLogger)(category);
165
+ const level = options.level ?? "info";
166
+ const formatOption = options.format ?? "combined";
167
+ const skip = options.skip ?? (() => false);
168
+ const logRequest = options.logRequest ?? false;
169
+ const scope = options.scope ?? "global";
170
+ const formatFn = typeof formatOption === "string" ? predefinedFormats[formatOption] : formatOption;
171
+ const logMethod = logger[level].bind(logger);
172
+ const errorLogMethod = logger.error.bind(logger);
173
+ let plugin = new elysia.Elysia({
174
+ name: "@logtape/elysia",
175
+ seed: options
176
+ }).state("startTime", 0).onRequest(({ store }) => {
177
+ store.startTime = performance.now();
178
+ });
179
+ if (logRequest) plugin = plugin.onRequest((ctx) => {
180
+ if (!skip(ctx)) {
181
+ const result = formatFn(ctx, 0);
182
+ if (typeof result === "string") logMethod(result);
183
+ else logMethod("{method} {url}", result);
184
+ }
185
+ });
186
+ else plugin = plugin.onAfterHandle((ctx) => {
187
+ if (skip(ctx)) return;
188
+ const store = ctx.store;
189
+ const responseTime = performance.now() - store.startTime;
190
+ const result = formatFn(ctx, responseTime);
191
+ if (typeof result === "string") logMethod(result);
192
+ else logMethod("{method} {url} {status} - {responseTime} ms", result);
193
+ });
194
+ plugin = plugin.onError((ctx) => {
195
+ const store = ctx.store;
196
+ const responseTime = performance.now() - store.startTime;
197
+ const elysiaCtx = ctx;
198
+ if (skip(elysiaCtx)) return;
199
+ const props = buildProperties(elysiaCtx, responseTime);
200
+ const error = ctx.error;
201
+ const errorMessage = error?.message ?? "Unknown error";
202
+ errorLogMethod("Error: {method} {url} {status} - {responseTime} ms - {errorMessage}", {
203
+ ...props,
204
+ errorMessage,
205
+ errorCode: ctx.code
206
+ });
207
+ });
208
+ if (scope === "global") return plugin.as("global");
209
+ else if (scope === "scoped") return plugin.as("scoped");
210
+ return plugin;
211
+ }
212
+
213
+ //#endregion
214
+ exports.elysiaLogger = elysiaLogger;
package/dist/mod.d.cts ADDED
@@ -0,0 +1,181 @@
1
+ import { Elysia } from "elysia";
2
+ import { LogLevel, LogLevel as LogLevel$1 } from "@logtape/logtape";
3
+
4
+ //#region src/mod.d.ts
5
+
6
+ /**
7
+ * Minimal Elysia Context interface for compatibility.
8
+ * @since 1.4.0
9
+ */
10
+ interface ElysiaContext {
11
+ request: Request;
12
+ path: string;
13
+ set: {
14
+ status: number;
15
+ headers: Record<string, string | undefined>;
16
+ };
17
+ }
18
+ /**
19
+ * Plugin scope options for controlling hook propagation.
20
+ * @since 1.4.0
21
+ */
22
+ type PluginScope = "global" | "scoped" | "local";
23
+ /**
24
+ * Predefined log format names compatible with Morgan.
25
+ * @since 1.4.0
26
+ */
27
+ type PredefinedFormat = "combined" | "common" | "dev" | "short" | "tiny";
28
+ /**
29
+ * Custom format function for request logging.
30
+ *
31
+ * @param ctx The Elysia context object.
32
+ * @param responseTime The response time in milliseconds.
33
+ * @returns A string message or an object with structured properties.
34
+ * @since 1.4.0
35
+ */
36
+ type FormatFunction = (ctx: ElysiaContext, responseTime: number) => string | Record<string, unknown>;
37
+ /**
38
+ * Structured log properties for HTTP requests.
39
+ * @since 1.4.0
40
+ */
41
+ interface RequestLogProperties {
42
+ /** HTTP request method */
43
+ method: string;
44
+ /** Request URL */
45
+ url: string;
46
+ /** Request path */
47
+ path: string;
48
+ /** HTTP response status code */
49
+ status: number;
50
+ /** Response time in milliseconds */
51
+ responseTime: number;
52
+ /** Response content-length header value */
53
+ contentLength: string | undefined;
54
+ /** Remote client address (from X-Forwarded-For header) */
55
+ remoteAddr: string | undefined;
56
+ /** User-Agent header value */
57
+ userAgent: string | undefined;
58
+ /** Referrer header value */
59
+ referrer: string | undefined;
60
+ }
61
+ /**
62
+ * Options for configuring the Elysia LogTape middleware.
63
+ * @since 1.4.0
64
+ */
65
+ interface ElysiaLogTapeOptions {
66
+ /**
67
+ * The LogTape category to use for logging.
68
+ * @default ["elysia"]
69
+ */
70
+ readonly category?: string | readonly string[];
71
+ /**
72
+ * The log level to use for request logging.
73
+ * @default "info"
74
+ */
75
+ readonly level?: LogLevel$1;
76
+ /**
77
+ * The format for log output.
78
+ * Can be a predefined format name or a custom format function.
79
+ *
80
+ * Predefined formats:
81
+ * - `"combined"` - Apache Combined Log Format (structured, default)
82
+ * - `"common"` - Apache Common Log Format (structured, no referrer/userAgent)
83
+ * - `"dev"` - Concise colored output for development (string)
84
+ * - `"short"` - Shorter than common (string)
85
+ * - `"tiny"` - Minimal output (string)
86
+ *
87
+ * @default "combined"
88
+ */
89
+ readonly format?: PredefinedFormat | FormatFunction;
90
+ /**
91
+ * Function to determine whether logging should be skipped.
92
+ * Return `true` to skip logging for a request.
93
+ *
94
+ * @example Skip logging for health check endpoint
95
+ * ```typescript
96
+ * app.use(elysiaLogger({
97
+ * skip: (ctx) => ctx.path === "/health",
98
+ * }));
99
+ * ```
100
+ *
101
+ * @default () => false
102
+ */
103
+ readonly skip?: (ctx: ElysiaContext) => boolean;
104
+ /**
105
+ * If `true`, logs are written immediately when the request is received.
106
+ * If `false` (default), logs are written after the response is sent.
107
+ *
108
+ * Note: When `logRequest` is `true`, response-related properties
109
+ * (status, responseTime, contentLength) will not be available.
110
+ *
111
+ * @default false
112
+ */
113
+ readonly logRequest?: boolean;
114
+ /**
115
+ * The plugin scope for controlling how lifecycle hooks are propagated.
116
+ *
117
+ * - `"global"` - Hooks apply to all routes in the application
118
+ * - `"scoped"` - Hooks apply to the parent instance where the plugin is used
119
+ * - `"local"` - Hooks only apply within the plugin itself
120
+ *
121
+ * @default "global"
122
+ */
123
+ readonly scope?: PluginScope;
124
+ }
125
+ /**
126
+ * Creates Elysia plugin for HTTP request logging using LogTape.
127
+ *
128
+ * This plugin provides Morgan-compatible request logging with LogTape
129
+ * as the backend, supporting structured logging and customizable formats.
130
+ *
131
+ * @example Basic usage
132
+ * ```typescript
133
+ * import { Elysia } from "elysia";
134
+ * import { configure, getConsoleSink } from "@logtape/logtape";
135
+ * import { elysiaLogger } from "@logtape/elysia";
136
+ *
137
+ * await configure({
138
+ * sinks: { console: getConsoleSink() },
139
+ * loggers: [
140
+ * { category: ["elysia"], sinks: ["console"], lowestLevel: "info" }
141
+ * ],
142
+ * });
143
+ *
144
+ * const app = new Elysia()
145
+ * .use(elysiaLogger())
146
+ * .get("/", () => ({ hello: "world" }))
147
+ * .listen(3000);
148
+ * ```
149
+ *
150
+ * @example With custom options
151
+ * ```typescript
152
+ * app.use(elysiaLogger({
153
+ * category: ["myapp", "http"],
154
+ * level: "debug",
155
+ * format: "dev",
156
+ * skip: (ctx) => ctx.path === "/health",
157
+ * scope: "scoped",
158
+ * }));
159
+ * ```
160
+ *
161
+ * @example With custom format function
162
+ * ```typescript
163
+ * app.use(elysiaLogger({
164
+ * format: (ctx, responseTime) => ({
165
+ * method: ctx.request.method,
166
+ * path: ctx.path,
167
+ * status: ctx.set.status,
168
+ * duration: responseTime,
169
+ * }),
170
+ * }));
171
+ * ```
172
+ *
173
+ * @param options Configuration options for the plugin.
174
+ * @returns Elysia plugin instance.
175
+ * @since 1.4.0
176
+ */
177
+ declare function elysiaLogger(options?: ElysiaLogTapeOptions): Elysia<any>;
178
+ //# sourceMappingURL=mod.d.ts.map
179
+ //#endregion
180
+ export { ElysiaContext, ElysiaLogTapeOptions, FormatFunction, LogLevel, PluginScope, PredefinedFormat, RequestLogProperties, elysiaLogger };
181
+ //# sourceMappingURL=mod.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.d.cts","names":[],"sources":["../src/mod.ts"],"sourcesContent":[],"mappings":";;;;;;AASA;;;AAKa,UALI,aAAA,CAKJ;EAAM,OAAA,EAJR,OAIQ;EAQP,IAAA,EAAA,MAAA;EAMA,GAAA,EAAA;IAUA,MAAA,EAAA,MAAc;IAAA,OAAA,EAxBb,MAwBa,CAAA,MAAA,EAAA,MAAA,GAAA,SAAA,CAAA;EAAA,CAAA;;AAGN;AAMpB;AAyBA;;AAWmB,KA7DP,WAAA,GA6DO,QAAA,GAAA,QAAA,GAAA,OAAA;;;;;AAoDW,KA3GlB,gBAAA,GA2GkB,UAAA,GAAA,QAAA,GAAA,KAAA,GAAA,OAAA,GAAA,MAAA;AAyM9B;;;;AAAwE;;;;KA1S5D,cAAA,SACL,iDAEO;;;;;UAMG,oBAAA;;;;;;;;;;;;;;;;;;;;;;;;UAyBA,oBAAA;;;;;;;;;;mBAWE;;;;;;;;;;;;;;oBAeC,mBAAmB;;;;;;;;;;;;;;wBAef;;;;;;;;;;;;;;;;;;;;mBAsBL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAyMH,YAAA,WAAsB,uBAA4B"}
package/dist/mod.d.ts ADDED
@@ -0,0 +1,181 @@
1
+ import { Elysia } from "elysia";
2
+ import { LogLevel, LogLevel as LogLevel$1 } from "@logtape/logtape";
3
+
4
+ //#region src/mod.d.ts
5
+
6
+ /**
7
+ * Minimal Elysia Context interface for compatibility.
8
+ * @since 1.4.0
9
+ */
10
+ interface ElysiaContext {
11
+ request: Request;
12
+ path: string;
13
+ set: {
14
+ status: number;
15
+ headers: Record<string, string | undefined>;
16
+ };
17
+ }
18
+ /**
19
+ * Plugin scope options for controlling hook propagation.
20
+ * @since 1.4.0
21
+ */
22
+ type PluginScope = "global" | "scoped" | "local";
23
+ /**
24
+ * Predefined log format names compatible with Morgan.
25
+ * @since 1.4.0
26
+ */
27
+ type PredefinedFormat = "combined" | "common" | "dev" | "short" | "tiny";
28
+ /**
29
+ * Custom format function for request logging.
30
+ *
31
+ * @param ctx The Elysia context object.
32
+ * @param responseTime The response time in milliseconds.
33
+ * @returns A string message or an object with structured properties.
34
+ * @since 1.4.0
35
+ */
36
+ type FormatFunction = (ctx: ElysiaContext, responseTime: number) => string | Record<string, unknown>;
37
+ /**
38
+ * Structured log properties for HTTP requests.
39
+ * @since 1.4.0
40
+ */
41
+ interface RequestLogProperties {
42
+ /** HTTP request method */
43
+ method: string;
44
+ /** Request URL */
45
+ url: string;
46
+ /** Request path */
47
+ path: string;
48
+ /** HTTP response status code */
49
+ status: number;
50
+ /** Response time in milliseconds */
51
+ responseTime: number;
52
+ /** Response content-length header value */
53
+ contentLength: string | undefined;
54
+ /** Remote client address (from X-Forwarded-For header) */
55
+ remoteAddr: string | undefined;
56
+ /** User-Agent header value */
57
+ userAgent: string | undefined;
58
+ /** Referrer header value */
59
+ referrer: string | undefined;
60
+ }
61
+ /**
62
+ * Options for configuring the Elysia LogTape middleware.
63
+ * @since 1.4.0
64
+ */
65
+ interface ElysiaLogTapeOptions {
66
+ /**
67
+ * The LogTape category to use for logging.
68
+ * @default ["elysia"]
69
+ */
70
+ readonly category?: string | readonly string[];
71
+ /**
72
+ * The log level to use for request logging.
73
+ * @default "info"
74
+ */
75
+ readonly level?: LogLevel$1;
76
+ /**
77
+ * The format for log output.
78
+ * Can be a predefined format name or a custom format function.
79
+ *
80
+ * Predefined formats:
81
+ * - `"combined"` - Apache Combined Log Format (structured, default)
82
+ * - `"common"` - Apache Common Log Format (structured, no referrer/userAgent)
83
+ * - `"dev"` - Concise colored output for development (string)
84
+ * - `"short"` - Shorter than common (string)
85
+ * - `"tiny"` - Minimal output (string)
86
+ *
87
+ * @default "combined"
88
+ */
89
+ readonly format?: PredefinedFormat | FormatFunction;
90
+ /**
91
+ * Function to determine whether logging should be skipped.
92
+ * Return `true` to skip logging for a request.
93
+ *
94
+ * @example Skip logging for health check endpoint
95
+ * ```typescript
96
+ * app.use(elysiaLogger({
97
+ * skip: (ctx) => ctx.path === "/health",
98
+ * }));
99
+ * ```
100
+ *
101
+ * @default () => false
102
+ */
103
+ readonly skip?: (ctx: ElysiaContext) => boolean;
104
+ /**
105
+ * If `true`, logs are written immediately when the request is received.
106
+ * If `false` (default), logs are written after the response is sent.
107
+ *
108
+ * Note: When `logRequest` is `true`, response-related properties
109
+ * (status, responseTime, contentLength) will not be available.
110
+ *
111
+ * @default false
112
+ */
113
+ readonly logRequest?: boolean;
114
+ /**
115
+ * The plugin scope for controlling how lifecycle hooks are propagated.
116
+ *
117
+ * - `"global"` - Hooks apply to all routes in the application
118
+ * - `"scoped"` - Hooks apply to the parent instance where the plugin is used
119
+ * - `"local"` - Hooks only apply within the plugin itself
120
+ *
121
+ * @default "global"
122
+ */
123
+ readonly scope?: PluginScope;
124
+ }
125
+ /**
126
+ * Creates Elysia plugin for HTTP request logging using LogTape.
127
+ *
128
+ * This plugin provides Morgan-compatible request logging with LogTape
129
+ * as the backend, supporting structured logging and customizable formats.
130
+ *
131
+ * @example Basic usage
132
+ * ```typescript
133
+ * import { Elysia } from "elysia";
134
+ * import { configure, getConsoleSink } from "@logtape/logtape";
135
+ * import { elysiaLogger } from "@logtape/elysia";
136
+ *
137
+ * await configure({
138
+ * sinks: { console: getConsoleSink() },
139
+ * loggers: [
140
+ * { category: ["elysia"], sinks: ["console"], lowestLevel: "info" }
141
+ * ],
142
+ * });
143
+ *
144
+ * const app = new Elysia()
145
+ * .use(elysiaLogger())
146
+ * .get("/", () => ({ hello: "world" }))
147
+ * .listen(3000);
148
+ * ```
149
+ *
150
+ * @example With custom options
151
+ * ```typescript
152
+ * app.use(elysiaLogger({
153
+ * category: ["myapp", "http"],
154
+ * level: "debug",
155
+ * format: "dev",
156
+ * skip: (ctx) => ctx.path === "/health",
157
+ * scope: "scoped",
158
+ * }));
159
+ * ```
160
+ *
161
+ * @example With custom format function
162
+ * ```typescript
163
+ * app.use(elysiaLogger({
164
+ * format: (ctx, responseTime) => ({
165
+ * method: ctx.request.method,
166
+ * path: ctx.path,
167
+ * status: ctx.set.status,
168
+ * duration: responseTime,
169
+ * }),
170
+ * }));
171
+ * ```
172
+ *
173
+ * @param options Configuration options for the plugin.
174
+ * @returns Elysia plugin instance.
175
+ * @since 1.4.0
176
+ */
177
+ declare function elysiaLogger(options?: ElysiaLogTapeOptions): Elysia<any>;
178
+ //# sourceMappingURL=mod.d.ts.map
179
+ //#endregion
180
+ export { ElysiaContext, ElysiaLogTapeOptions, FormatFunction, LogLevel, PluginScope, PredefinedFormat, RequestLogProperties, elysiaLogger };
181
+ //# sourceMappingURL=mod.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.d.ts","names":[],"sources":["../src/mod.ts"],"sourcesContent":[],"mappings":";;;;;;AASA;;;AAKa,UALI,aAAA,CAKJ;EAAM,OAAA,EAJR,OAIQ;EAQP,IAAA,EAAA,MAAA;EAMA,GAAA,EAAA;IAUA,MAAA,EAAA,MAAc;IAAA,OAAA,EAxBb,MAwBa,CAAA,MAAA,EAAA,MAAA,GAAA,SAAA,CAAA;EAAA,CAAA;;AAGN;AAMpB;AAyBA;;AAWmB,KA7DP,WAAA,GA6DO,QAAA,GAAA,QAAA,GAAA,OAAA;;;;;AAoDW,KA3GlB,gBAAA,GA2GkB,UAAA,GAAA,QAAA,GAAA,KAAA,GAAA,OAAA,GAAA,MAAA;AAyM9B;;;;AAAwE;;;;KA1S5D,cAAA,SACL,iDAEO;;;;;UAMG,oBAAA;;;;;;;;;;;;;;;;;;;;;;;;UAyBA,oBAAA;;;;;;;;;;mBAWE;;;;;;;;;;;;;;oBAeC,mBAAmB;;;;;;;;;;;;;;wBAef;;;;;;;;;;;;;;;;;;;;mBAsBL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAyMH,YAAA,WAAsB,uBAA4B"}
package/dist/mod.js ADDED
@@ -0,0 +1,214 @@
1
+ import { Elysia } from "elysia";
2
+ import { getLogger } from "@logtape/logtape";
3
+
4
+ //#region src/mod.ts
5
+ /**
6
+ * Get referrer from request headers.
7
+ */
8
+ function getReferrer(request) {
9
+ return request.headers.get("referrer") ?? request.headers.get("referer") ?? void 0;
10
+ }
11
+ /**
12
+ * Get user agent from request headers.
13
+ */
14
+ function getUserAgent(request) {
15
+ return request.headers.get("user-agent") ?? void 0;
16
+ }
17
+ /**
18
+ * Get remote address from X-Forwarded-For header.
19
+ */
20
+ function getRemoteAddr(request) {
21
+ const forwarded = request.headers.get("x-forwarded-for");
22
+ if (forwarded) {
23
+ const firstIp = forwarded.split(",")[0].trim();
24
+ return firstIp || void 0;
25
+ }
26
+ return void 0;
27
+ }
28
+ /**
29
+ * Get content length from response headers.
30
+ */
31
+ function getContentLength(headers) {
32
+ const contentLength = headers["content-length"];
33
+ if (contentLength === void 0 || contentLength === null) return void 0;
34
+ return contentLength;
35
+ }
36
+ /**
37
+ * Build structured log properties from context.
38
+ */
39
+ function buildProperties(ctx, responseTime) {
40
+ return {
41
+ method: ctx.request.method,
42
+ url: ctx.request.url,
43
+ path: ctx.path,
44
+ status: ctx.set.status,
45
+ responseTime,
46
+ contentLength: getContentLength(ctx.set.headers),
47
+ remoteAddr: getRemoteAddr(ctx.request),
48
+ userAgent: getUserAgent(ctx.request),
49
+ referrer: getReferrer(ctx.request)
50
+ };
51
+ }
52
+ /**
53
+ * Combined format (Apache Combined Log Format).
54
+ * Returns all structured properties.
55
+ */
56
+ function formatCombined(ctx, responseTime) {
57
+ return { ...buildProperties(ctx, responseTime) };
58
+ }
59
+ /**
60
+ * Common format (Apache Common Log Format).
61
+ * Like combined but without referrer and userAgent.
62
+ */
63
+ function formatCommon(ctx, responseTime) {
64
+ const props = buildProperties(ctx, responseTime);
65
+ const { referrer: _referrer, userAgent: _userAgent,...rest } = props;
66
+ return rest;
67
+ }
68
+ /**
69
+ * Dev format (colored output for development).
70
+ * :method :path :status :response-time ms - :res[content-length]
71
+ */
72
+ function formatDev(ctx, responseTime) {
73
+ const contentLength = getContentLength(ctx.set.headers) ?? "-";
74
+ return `${ctx.request.method} ${ctx.path} ${ctx.set.status} ${responseTime.toFixed(3)} ms - ${contentLength}`;
75
+ }
76
+ /**
77
+ * Short format.
78
+ * :remote-addr :method :url :status :res[content-length] - :response-time ms
79
+ */
80
+ function formatShort(ctx, responseTime) {
81
+ const remoteAddr = getRemoteAddr(ctx.request) ?? "-";
82
+ const contentLength = getContentLength(ctx.set.headers) ?? "-";
83
+ return `${remoteAddr} ${ctx.request.method} ${ctx.request.url} ${ctx.set.status} ${contentLength} - ${responseTime.toFixed(3)} ms`;
84
+ }
85
+ /**
86
+ * Tiny format (minimal output).
87
+ * :method :path :status :res[content-length] - :response-time ms
88
+ */
89
+ function formatTiny(ctx, responseTime) {
90
+ const contentLength = getContentLength(ctx.set.headers) ?? "-";
91
+ return `${ctx.request.method} ${ctx.path} ${ctx.set.status} ${contentLength} - ${responseTime.toFixed(3)} ms`;
92
+ }
93
+ /**
94
+ * Map of predefined format functions.
95
+ */
96
+ const predefinedFormats = {
97
+ combined: formatCombined,
98
+ common: formatCommon,
99
+ dev: formatDev,
100
+ short: formatShort,
101
+ tiny: formatTiny
102
+ };
103
+ /**
104
+ * Normalize category to array format.
105
+ */
106
+ function normalizeCategory(category) {
107
+ return typeof category === "string" ? [category] : category;
108
+ }
109
+ /**
110
+ * Creates Elysia plugin for HTTP request logging using LogTape.
111
+ *
112
+ * This plugin provides Morgan-compatible request logging with LogTape
113
+ * as the backend, supporting structured logging and customizable formats.
114
+ *
115
+ * @example Basic usage
116
+ * ```typescript
117
+ * import { Elysia } from "elysia";
118
+ * import { configure, getConsoleSink } from "@logtape/logtape";
119
+ * import { elysiaLogger } from "@logtape/elysia";
120
+ *
121
+ * await configure({
122
+ * sinks: { console: getConsoleSink() },
123
+ * loggers: [
124
+ * { category: ["elysia"], sinks: ["console"], lowestLevel: "info" }
125
+ * ],
126
+ * });
127
+ *
128
+ * const app = new Elysia()
129
+ * .use(elysiaLogger())
130
+ * .get("/", () => ({ hello: "world" }))
131
+ * .listen(3000);
132
+ * ```
133
+ *
134
+ * @example With custom options
135
+ * ```typescript
136
+ * app.use(elysiaLogger({
137
+ * category: ["myapp", "http"],
138
+ * level: "debug",
139
+ * format: "dev",
140
+ * skip: (ctx) => ctx.path === "/health",
141
+ * scope: "scoped",
142
+ * }));
143
+ * ```
144
+ *
145
+ * @example With custom format function
146
+ * ```typescript
147
+ * app.use(elysiaLogger({
148
+ * format: (ctx, responseTime) => ({
149
+ * method: ctx.request.method,
150
+ * path: ctx.path,
151
+ * status: ctx.set.status,
152
+ * duration: responseTime,
153
+ * }),
154
+ * }));
155
+ * ```
156
+ *
157
+ * @param options Configuration options for the plugin.
158
+ * @returns Elysia plugin instance.
159
+ * @since 1.4.0
160
+ */
161
+ function elysiaLogger(options = {}) {
162
+ const category = normalizeCategory(options.category ?? ["elysia"]);
163
+ const logger = getLogger(category);
164
+ const level = options.level ?? "info";
165
+ const formatOption = options.format ?? "combined";
166
+ const skip = options.skip ?? (() => false);
167
+ const logRequest = options.logRequest ?? false;
168
+ const scope = options.scope ?? "global";
169
+ const formatFn = typeof formatOption === "string" ? predefinedFormats[formatOption] : formatOption;
170
+ const logMethod = logger[level].bind(logger);
171
+ const errorLogMethod = logger.error.bind(logger);
172
+ let plugin = new Elysia({
173
+ name: "@logtape/elysia",
174
+ seed: options
175
+ }).state("startTime", 0).onRequest(({ store }) => {
176
+ store.startTime = performance.now();
177
+ });
178
+ if (logRequest) plugin = plugin.onRequest((ctx) => {
179
+ if (!skip(ctx)) {
180
+ const result = formatFn(ctx, 0);
181
+ if (typeof result === "string") logMethod(result);
182
+ else logMethod("{method} {url}", result);
183
+ }
184
+ });
185
+ else plugin = plugin.onAfterHandle((ctx) => {
186
+ if (skip(ctx)) return;
187
+ const store = ctx.store;
188
+ const responseTime = performance.now() - store.startTime;
189
+ const result = formatFn(ctx, responseTime);
190
+ if (typeof result === "string") logMethod(result);
191
+ else logMethod("{method} {url} {status} - {responseTime} ms", result);
192
+ });
193
+ plugin = plugin.onError((ctx) => {
194
+ const store = ctx.store;
195
+ const responseTime = performance.now() - store.startTime;
196
+ const elysiaCtx = ctx;
197
+ if (skip(elysiaCtx)) return;
198
+ const props = buildProperties(elysiaCtx, responseTime);
199
+ const error = ctx.error;
200
+ const errorMessage = error?.message ?? "Unknown error";
201
+ errorLogMethod("Error: {method} {url} {status} - {responseTime} ms - {errorMessage}", {
202
+ ...props,
203
+ errorMessage,
204
+ errorCode: ctx.code
205
+ });
206
+ });
207
+ if (scope === "global") return plugin.as("global");
208
+ else if (scope === "scoped") return plugin.as("scoped");
209
+ return plugin;
210
+ }
211
+
212
+ //#endregion
213
+ export { elysiaLogger };
214
+ //# sourceMappingURL=mod.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.js","names":["request: Request","headers: Record<string, string | undefined>","ctx: ElysiaContext","responseTime: number","predefinedFormats: Record<PredefinedFormat, FormatFunction>","category: string | readonly string[]","options: ElysiaLogTapeOptions","formatFn: FormatFunction"],"sources":["../src/mod.ts"],"sourcesContent":["import { Elysia } from \"elysia\";\nimport { getLogger, type LogLevel } from \"@logtape/logtape\";\n\nexport type { LogLevel } from \"@logtape/logtape\";\n\n/**\n * Minimal Elysia Context interface for compatibility.\n * @since 1.4.0\n */\nexport interface ElysiaContext {\n request: Request;\n path: string;\n set: {\n status: number;\n headers: Record<string, string | undefined>;\n };\n}\n\n/**\n * Plugin scope options for controlling hook propagation.\n * @since 1.4.0\n */\nexport type PluginScope = \"global\" | \"scoped\" | \"local\";\n\n/**\n * Predefined log format names compatible with Morgan.\n * @since 1.4.0\n */\nexport type PredefinedFormat = \"combined\" | \"common\" | \"dev\" | \"short\" | \"tiny\";\n\n/**\n * Custom format function for request logging.\n *\n * @param ctx The Elysia context object.\n * @param responseTime The response time in milliseconds.\n * @returns A string message or an object with structured properties.\n * @since 1.4.0\n */\nexport type FormatFunction = (\n ctx: ElysiaContext,\n responseTime: number,\n) => string | Record<string, unknown>;\n\n/**\n * Structured log properties for HTTP requests.\n * @since 1.4.0\n */\nexport interface RequestLogProperties {\n /** HTTP request method */\n method: string;\n /** Request URL */\n url: string;\n /** Request path */\n path: string;\n /** HTTP response status code */\n status: number;\n /** Response time in milliseconds */\n responseTime: number;\n /** Response content-length header value */\n contentLength: string | undefined;\n /** Remote client address (from X-Forwarded-For header) */\n remoteAddr: string | undefined;\n /** User-Agent header value */\n userAgent: string | undefined;\n /** Referrer header value */\n referrer: string | undefined;\n}\n\n/**\n * Options for configuring the Elysia LogTape middleware.\n * @since 1.4.0\n */\nexport interface ElysiaLogTapeOptions {\n /**\n * The LogTape category to use for logging.\n * @default [\"elysia\"]\n */\n readonly category?: string | readonly string[];\n\n /**\n * The log level to use for request logging.\n * @default \"info\"\n */\n readonly level?: LogLevel;\n\n /**\n * The format for log output.\n * Can be a predefined format name or a custom format function.\n *\n * Predefined formats:\n * - `\"combined\"` - Apache Combined Log Format (structured, default)\n * - `\"common\"` - Apache Common Log Format (structured, no referrer/userAgent)\n * - `\"dev\"` - Concise colored output for development (string)\n * - `\"short\"` - Shorter than common (string)\n * - `\"tiny\"` - Minimal output (string)\n *\n * @default \"combined\"\n */\n readonly format?: PredefinedFormat | FormatFunction;\n\n /**\n * Function to determine whether logging should be skipped.\n * Return `true` to skip logging for a request.\n *\n * @example Skip logging for health check endpoint\n * ```typescript\n * app.use(elysiaLogger({\n * skip: (ctx) => ctx.path === \"/health\",\n * }));\n * ```\n *\n * @default () => false\n */\n readonly skip?: (ctx: ElysiaContext) => boolean;\n\n /**\n * If `true`, logs are written immediately when the request is received.\n * If `false` (default), logs are written after the response is sent.\n *\n * Note: When `logRequest` is `true`, response-related properties\n * (status, responseTime, contentLength) will not be available.\n *\n * @default false\n */\n readonly logRequest?: boolean;\n\n /**\n * The plugin scope for controlling how lifecycle hooks are propagated.\n *\n * - `\"global\"` - Hooks apply to all routes in the application\n * - `\"scoped\"` - Hooks apply to the parent instance where the plugin is used\n * - `\"local\"` - Hooks only apply within the plugin itself\n *\n * @default \"global\"\n */\n readonly scope?: PluginScope;\n}\n\n/**\n * Get referrer from request headers.\n */\nfunction getReferrer(request: Request): string | undefined {\n return request.headers.get(\"referrer\") ??\n request.headers.get(\"referer\") ??\n undefined;\n}\n\n/**\n * Get user agent from request headers.\n */\nfunction getUserAgent(request: Request): string | undefined {\n return request.headers.get(\"user-agent\") ?? undefined;\n}\n\n/**\n * Get remote address from X-Forwarded-For header.\n */\nfunction getRemoteAddr(request: Request): string | undefined {\n const forwarded = request.headers.get(\"x-forwarded-for\");\n if (forwarded) {\n // X-Forwarded-For can contain multiple IPs, take the first one\n const firstIp = forwarded.split(\",\")[0].trim();\n return firstIp || undefined;\n }\n return undefined;\n}\n\n/**\n * Get content length from response headers.\n */\nfunction getContentLength(\n headers: Record<string, string | undefined>,\n): string | undefined {\n const contentLength = headers[\"content-length\"];\n if (contentLength === undefined || contentLength === null) return undefined;\n return contentLength;\n}\n\n/**\n * Build structured log properties from context.\n */\nfunction buildProperties(\n ctx: ElysiaContext,\n responseTime: number,\n): RequestLogProperties {\n return {\n method: ctx.request.method,\n url: ctx.request.url,\n path: ctx.path,\n status: ctx.set.status,\n responseTime,\n contentLength: getContentLength(ctx.set.headers),\n remoteAddr: getRemoteAddr(ctx.request),\n userAgent: getUserAgent(ctx.request),\n referrer: getReferrer(ctx.request),\n };\n}\n\n/**\n * Combined format (Apache Combined Log Format).\n * Returns all structured properties.\n */\nfunction formatCombined(\n ctx: ElysiaContext,\n responseTime: number,\n): Record<string, unknown> {\n return { ...buildProperties(ctx, responseTime) };\n}\n\n/**\n * Common format (Apache Common Log Format).\n * Like combined but without referrer and userAgent.\n */\nfunction formatCommon(\n ctx: ElysiaContext,\n responseTime: number,\n): Record<string, unknown> {\n const props = buildProperties(ctx, responseTime);\n const { referrer: _referrer, userAgent: _userAgent, ...rest } = props;\n return rest;\n}\n\n/**\n * Dev format (colored output for development).\n * :method :path :status :response-time ms - :res[content-length]\n */\nfunction formatDev(ctx: ElysiaContext, responseTime: number): string {\n const contentLength = getContentLength(ctx.set.headers) ?? \"-\";\n return `${ctx.request.method} ${ctx.path} ${ctx.set.status} ${\n responseTime.toFixed(3)\n } ms - ${contentLength}`;\n}\n\n/**\n * Short format.\n * :remote-addr :method :url :status :res[content-length] - :response-time ms\n */\nfunction formatShort(ctx: ElysiaContext, responseTime: number): string {\n const remoteAddr = getRemoteAddr(ctx.request) ?? \"-\";\n const contentLength = getContentLength(ctx.set.headers) ?? \"-\";\n return `${remoteAddr} ${ctx.request.method} ${ctx.request.url} ${ctx.set.status} ${contentLength} - ${\n responseTime.toFixed(3)\n } ms`;\n}\n\n/**\n * Tiny format (minimal output).\n * :method :path :status :res[content-length] - :response-time ms\n */\nfunction formatTiny(ctx: ElysiaContext, responseTime: number): string {\n const contentLength = getContentLength(ctx.set.headers) ?? \"-\";\n return `${ctx.request.method} ${ctx.path} ${ctx.set.status} ${contentLength} - ${\n responseTime.toFixed(3)\n } ms`;\n}\n\n/**\n * Map of predefined format functions.\n */\nconst predefinedFormats: Record<PredefinedFormat, FormatFunction> = {\n combined: formatCombined,\n common: formatCommon,\n dev: formatDev,\n short: formatShort,\n tiny: formatTiny,\n};\n\n/**\n * Normalize category to array format.\n */\nfunction normalizeCategory(\n category: string | readonly string[],\n): readonly string[] {\n return typeof category === \"string\" ? [category] : category;\n}\n\n/**\n * Internal store type for timing.\n */\ninterface LoggerStore {\n startTime: number;\n}\n\n/**\n * Creates Elysia plugin for HTTP request logging using LogTape.\n *\n * This plugin provides Morgan-compatible request logging with LogTape\n * as the backend, supporting structured logging and customizable formats.\n *\n * @example Basic usage\n * ```typescript\n * import { Elysia } from \"elysia\";\n * import { configure, getConsoleSink } from \"@logtape/logtape\";\n * import { elysiaLogger } from \"@logtape/elysia\";\n *\n * await configure({\n * sinks: { console: getConsoleSink() },\n * loggers: [\n * { category: [\"elysia\"], sinks: [\"console\"], lowestLevel: \"info\" }\n * ],\n * });\n *\n * const app = new Elysia()\n * .use(elysiaLogger())\n * .get(\"/\", () => ({ hello: \"world\" }))\n * .listen(3000);\n * ```\n *\n * @example With custom options\n * ```typescript\n * app.use(elysiaLogger({\n * category: [\"myapp\", \"http\"],\n * level: \"debug\",\n * format: \"dev\",\n * skip: (ctx) => ctx.path === \"/health\",\n * scope: \"scoped\",\n * }));\n * ```\n *\n * @example With custom format function\n * ```typescript\n * app.use(elysiaLogger({\n * format: (ctx, responseTime) => ({\n * method: ctx.request.method,\n * path: ctx.path,\n * status: ctx.set.status,\n * duration: responseTime,\n * }),\n * }));\n * ```\n *\n * @param options Configuration options for the plugin.\n * @returns Elysia plugin instance.\n * @since 1.4.0\n */\n// deno-lint-ignore no-explicit-any\nexport function elysiaLogger(options: ElysiaLogTapeOptions = {}): Elysia<any> {\n const category = normalizeCategory(options.category ?? [\"elysia\"]);\n const logger = getLogger(category);\n const level = options.level ?? \"info\";\n const formatOption = options.format ?? \"combined\";\n const skip = options.skip ?? (() => false);\n const logRequest = options.logRequest ?? false;\n const scope = options.scope ?? \"global\";\n\n // Resolve format function\n const formatFn: FormatFunction = typeof formatOption === \"string\"\n ? predefinedFormats[formatOption]\n : formatOption;\n\n const logMethod = logger[level].bind(logger);\n const errorLogMethod = logger.error.bind(logger);\n\n let plugin = new Elysia({\n name: \"@logtape/elysia\",\n seed: options,\n })\n .state(\"startTime\", 0)\n .onRequest(({ store }) => {\n (store as LoggerStore).startTime = performance.now();\n });\n\n if (logRequest) {\n // Log immediately when request arrives\n plugin = plugin.onRequest((ctx) => {\n if (!skip(ctx as unknown as ElysiaContext)) {\n const result = formatFn(ctx as unknown as ElysiaContext, 0);\n if (typeof result === \"string\") {\n logMethod(result);\n } else {\n logMethod(\"{method} {url}\", result);\n }\n }\n });\n } else {\n // Log after handler completes\n plugin = plugin.onAfterHandle((ctx) => {\n if (skip(ctx as unknown as ElysiaContext)) return;\n\n const store = ctx.store as LoggerStore;\n const responseTime = performance.now() - store.startTime;\n const result = formatFn(ctx as unknown as ElysiaContext, responseTime);\n\n if (typeof result === \"string\") {\n logMethod(result);\n } else {\n logMethod(\"{method} {url} {status} - {responseTime} ms\", result);\n }\n });\n }\n\n // Add error logging\n plugin = plugin.onError((ctx) => {\n const store = ctx.store as LoggerStore;\n const responseTime = performance.now() - store.startTime;\n const elysiaCtx = ctx as unknown as ElysiaContext;\n\n if (skip(elysiaCtx)) return;\n\n const props = buildProperties(elysiaCtx, responseTime);\n // Extract error message safely\n const error = ctx.error as { message?: string } | undefined;\n const errorMessage = error?.message ?? \"Unknown error\";\n errorLogMethod(\n \"Error: {method} {url} {status} - {responseTime} ms - {errorMessage}\",\n {\n ...props,\n errorMessage,\n errorCode: ctx.code,\n },\n );\n });\n\n // Apply scope\n if (scope === \"global\") {\n // deno-lint-ignore no-explicit-any\n return plugin.as(\"global\") as unknown as Elysia<any>;\n } else if (scope === \"scoped\") {\n // deno-lint-ignore no-explicit-any\n return plugin.as(\"scoped\") as unknown as Elysia<any>;\n }\n\n // deno-lint-ignore no-explicit-any\n return plugin as unknown as Elysia<any>;\n}\n"],"mappings":"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"}
package/package.json ADDED
@@ -0,0 +1,75 @@
1
+ {
2
+ "name": "@logtape/elysia",
3
+ "version": "1.4.0-dev.1",
4
+ "description": "Elysia adapter for LogTape logging library",
5
+ "keywords": [
6
+ "logging",
7
+ "log",
8
+ "logger",
9
+ "elysia",
10
+ "elysiajs",
11
+ "middleware",
12
+ "http",
13
+ "request",
14
+ "adapter",
15
+ "logtape",
16
+ "bun"
17
+ ],
18
+ "license": "MIT",
19
+ "author": {
20
+ "name": "Hong Minhee",
21
+ "email": "hong@minhee.org",
22
+ "url": "https://hongminhee.org/"
23
+ },
24
+ "homepage": "https://logtape.org/",
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/dahlia/logtape.git",
28
+ "directory": "packages/elysia/"
29
+ },
30
+ "bugs": {
31
+ "url": "https://github.com/dahlia/logtape/issues"
32
+ },
33
+ "funding": [
34
+ "https://github.com/sponsors/dahlia"
35
+ ],
36
+ "type": "module",
37
+ "module": "./dist/mod.js",
38
+ "main": "./dist/mod.cjs",
39
+ "types": "./dist/mod.d.ts",
40
+ "exports": {
41
+ ".": {
42
+ "types": {
43
+ "import": "./dist/mod.d.ts",
44
+ "require": "./dist/mod.d.cts"
45
+ },
46
+ "import": "./dist/mod.js",
47
+ "require": "./dist/mod.cjs"
48
+ },
49
+ "./package.json": "./package.json"
50
+ },
51
+ "sideEffects": false,
52
+ "files": [
53
+ "dist/"
54
+ ],
55
+ "peerDependencies": {
56
+ "elysia": "^1.4.0",
57
+ "@logtape/logtape": "^1.4.0"
58
+ },
59
+ "devDependencies": {
60
+ "@alinea/suite": "^0.6.3",
61
+ "@std/assert": "npm:@jsr/std__assert@^1.0.13",
62
+ "@std/async": "npm:@jsr/std__async@^1.0.13",
63
+ "elysia": "^1.4.0",
64
+ "tsdown": "^0.12.7",
65
+ "typescript": "^5.8.3"
66
+ },
67
+ "scripts": {
68
+ "build": "tsdown",
69
+ "prepublish": "tsdown",
70
+ "test": "tsdown && node --experimental-transform-types --test",
71
+ "test:bun": "tsdown && bun test",
72
+ "test:deno": "deno test --allow-env --allow-sys --allow-net",
73
+ "test-all": "tsdown && node --experimental-transform-types --test && bun test && deno test"
74
+ }
75
+ }