@logtape/express 1.3.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,104 @@
1
+ <!-- deno-fmt-ignore-file -->
2
+
3
+ @logtape/express
4
+ ================
5
+
6
+ [![JSR][JSR badge]][JSR]
7
+ [![npm][npm badge]][npm]
8
+
9
+ *@logtape/express* is an [Express] middleware adapter that provides HTTP
10
+ request logging using [LogTape] as the backend, as an alternative to [Morgan].
11
+
12
+ [JSR]: https://jsr.io/@logtape/express
13
+ [JSR badge]: https://jsr.io/badges/@logtape/express
14
+ [npm]: https://www.npmjs.com/package/@logtape/express
15
+ [npm badge]: https://img.shields.io/npm/v/@logtape/express?logo=npm
16
+ [LogTape]: https://logtape.org/
17
+ [Express]: https://expressjs.com/
18
+ [Morgan]: https://github.com/expressjs/morgan
19
+
20
+
21
+ Installation
22
+ ------------
23
+
24
+ ~~~~ sh
25
+ deno add jsr:@logtape/express # for Deno
26
+ npm add @logtape/express # for npm
27
+ pnpm add @logtape/express # for pnpm
28
+ yarn add @logtape/express # for Yarn
29
+ bun add @logtape/express # for Bun
30
+ ~~~~
31
+
32
+
33
+ Usage
34
+ -----
35
+
36
+ ~~~~ typescript
37
+ import { configure, getConsoleSink } from "@logtape/logtape";
38
+ import { expressLogger } from "@logtape/express";
39
+ import express from "express";
40
+
41
+ await configure({
42
+ sinks: { console: getConsoleSink() },
43
+ loggers: [
44
+ { category: ["express"], sinks: ["console"], lowestLevel: "info" }
45
+ ],
46
+ });
47
+
48
+ const app = express();
49
+ app.use(expressLogger());
50
+
51
+ app.get("/", (req, res) => {
52
+ res.json({ hello: "world" });
53
+ });
54
+
55
+ app.listen(3000);
56
+ ~~~~
57
+
58
+
59
+ Options
60
+ -------
61
+
62
+ ~~~~ typescript
63
+ app.use(expressLogger({
64
+ category: ["myapp", "http"], // Custom category (default: ["express"])
65
+ level: "debug", // Log level (default: "info")
66
+ format: "dev", // Predefined format (default: "combined")
67
+ skip: (req, res) => res.statusCode < 400, // Skip successful requests
68
+ immediate: false, // Log after response (default)
69
+ }));
70
+ ~~~~
71
+
72
+
73
+ Predefined Formats
74
+ ------------------
75
+
76
+ - **combined**: Apache Combined Log Format with all properties (default)
77
+ - **common**: Apache Common Log Format (without referrer/userAgent)
78
+ - **dev**: Concise output for development (`GET /path 200 1.234 ms - 123`)
79
+ - **short**: Shorter format with remote address
80
+ - **tiny**: Minimal output
81
+
82
+
83
+ Custom Format Function
84
+ ----------------------
85
+
86
+ ~~~~ typescript
87
+ app.use(expressLogger({
88
+ format: (req, res, responseTime) => ({
89
+ method: req.method,
90
+ path: req.path,
91
+ status: res.statusCode,
92
+ duration: responseTime,
93
+ user: req.user?.id,
94
+ }),
95
+ }));
96
+ ~~~~
97
+
98
+
99
+ Docs
100
+ ----
101
+
102
+ The docs of this package is available at
103
+ <https://logtape.org/manual/integrations#express>.
104
+ For the API references, see <https://jsr.io/@logtape/express/doc>.
package/deno.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@logtape/express",
3
+ "version": "1.3.0",
4
+ "license": "MIT",
5
+ "exports": "./src/mod.ts",
6
+ "exclude": [
7
+ "coverage/",
8
+ "npm/",
9
+ "dist/"
10
+ ],
11
+ "tasks": {
12
+ "build": "pnpm build",
13
+ "test": "deno test --allow-env --allow-sys --allow-net",
14
+ "test:node": {
15
+ "dependencies": [
16
+ "build"
17
+ ],
18
+ "command": "node --experimental-transform-types --test"
19
+ },
20
+ "test:bun": {
21
+ "dependencies": [
22
+ "build"
23
+ ],
24
+ "command": "bun test"
25
+ },
26
+ "test-all": {
27
+ "dependencies": [
28
+ "test",
29
+ "test:node",
30
+ "test:bun"
31
+ ]
32
+ }
33
+ }
34
+ }
@@ -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,192 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ const __logtape_logtape = require_rolldown_runtime.__toESM(require("@logtape/logtape"));
3
+
4
+ //#region src/mod.ts
5
+ /**
6
+ * Get remote address from request.
7
+ */
8
+ function getRemoteAddr(req) {
9
+ return req.ip || req.socket?.remoteAddress;
10
+ }
11
+ /**
12
+ * Get content length from response headers.
13
+ */
14
+ function getContentLength(res) {
15
+ const contentLength = res.getHeader("content-length");
16
+ if (contentLength === void 0 || contentLength === null) return void 0;
17
+ return String(contentLength);
18
+ }
19
+ /**
20
+ * Get referrer from request headers.
21
+ */
22
+ function getReferrer(req) {
23
+ return req.get("referrer") || req.get("referer");
24
+ }
25
+ /**
26
+ * Get user agent from request headers.
27
+ */
28
+ function getUserAgent(req) {
29
+ return req.get("user-agent");
30
+ }
31
+ /**
32
+ * Build structured log properties from request/response.
33
+ */
34
+ function buildProperties(req, res, responseTime) {
35
+ return {
36
+ method: req.method,
37
+ url: req.originalUrl || req.url,
38
+ status: res.statusCode,
39
+ responseTime,
40
+ contentLength: getContentLength(res),
41
+ remoteAddr: getRemoteAddr(req),
42
+ userAgent: getUserAgent(req),
43
+ referrer: getReferrer(req),
44
+ httpVersion: req.httpVersion
45
+ };
46
+ }
47
+ /**
48
+ * Combined format (Apache Combined Log Format).
49
+ * Returns all structured properties.
50
+ */
51
+ function formatCombined(req, res, responseTime) {
52
+ return { ...buildProperties(req, res, responseTime) };
53
+ }
54
+ /**
55
+ * Common format (Apache Common Log Format).
56
+ * Like combined but without referrer and userAgent.
57
+ */
58
+ function formatCommon(req, res, responseTime) {
59
+ const props = buildProperties(req, res, responseTime);
60
+ const { referrer: _referrer, userAgent: _userAgent,...rest } = props;
61
+ return rest;
62
+ }
63
+ /**
64
+ * Dev format (colored output for development).
65
+ * :method :url :status :response-time ms - :res[content-length]
66
+ */
67
+ function formatDev(req, res, responseTime) {
68
+ const contentLength = getContentLength(res) ?? "-";
69
+ return `${req.method} ${req.originalUrl || req.url} ${res.statusCode} ${responseTime.toFixed(3)} ms - ${contentLength}`;
70
+ }
71
+ /**
72
+ * Short format.
73
+ * :remote-addr :method :url HTTP/:http-version :status :res[content-length] - :response-time ms
74
+ */
75
+ function formatShort(req, res, responseTime) {
76
+ const remoteAddr = getRemoteAddr(req) ?? "-";
77
+ const contentLength = getContentLength(res) ?? "-";
78
+ return `${remoteAddr} ${req.method} ${req.originalUrl || req.url} HTTP/${req.httpVersion} ${res.statusCode} ${contentLength} - ${responseTime.toFixed(3)} ms`;
79
+ }
80
+ /**
81
+ * Tiny format (minimal output).
82
+ * :method :url :status :res[content-length] - :response-time ms
83
+ */
84
+ function formatTiny(req, res, responseTime) {
85
+ const contentLength = getContentLength(res) ?? "-";
86
+ return `${req.method} ${req.originalUrl || req.url} ${res.statusCode} ${contentLength} - ${responseTime.toFixed(3)} ms`;
87
+ }
88
+ /**
89
+ * Map of predefined format functions.
90
+ */
91
+ const predefinedFormats = {
92
+ combined: formatCombined,
93
+ common: formatCommon,
94
+ dev: formatDev,
95
+ short: formatShort,
96
+ tiny: formatTiny
97
+ };
98
+ /**
99
+ * Normalize category to array format.
100
+ */
101
+ function normalizeCategory(category) {
102
+ return typeof category === "string" ? [category] : category;
103
+ }
104
+ /**
105
+ * Creates Express middleware for HTTP request logging using LogTape.
106
+ *
107
+ * This middleware provides Morgan-compatible request logging with LogTape
108
+ * as the backend, supporting structured logging and customizable formats.
109
+ *
110
+ * @example Basic usage
111
+ * ```typescript
112
+ * import express from "express";
113
+ * import { configure, getConsoleSink } from "@logtape/logtape";
114
+ * import { expressLogger } from "@logtape/express";
115
+ *
116
+ * await configure({
117
+ * sinks: { console: getConsoleSink() },
118
+ * loggers: [
119
+ * { category: ["express"], sinks: ["console"], lowestLevel: "info" }
120
+ * ],
121
+ * });
122
+ *
123
+ * const app = express();
124
+ * app.use(expressLogger());
125
+ *
126
+ * app.get("/", (req, res) => {
127
+ * res.json({ hello: "world" });
128
+ * });
129
+ *
130
+ * app.listen(3000);
131
+ * ```
132
+ *
133
+ * @example With custom options
134
+ * ```typescript
135
+ * app.use(expressLogger({
136
+ * category: ["myapp", "http"],
137
+ * level: "debug",
138
+ * format: "dev",
139
+ * skip: (req, res) => res.statusCode < 400,
140
+ * }));
141
+ * ```
142
+ *
143
+ * @example With custom format function
144
+ * ```typescript
145
+ * app.use(expressLogger({
146
+ * format: (req, res, responseTime) => ({
147
+ * method: req.method,
148
+ * path: req.path,
149
+ * status: res.statusCode,
150
+ * duration: responseTime,
151
+ * }),
152
+ * }));
153
+ * ```
154
+ *
155
+ * @param options Configuration options for the middleware.
156
+ * @returns Express middleware function.
157
+ * @since 1.3.0
158
+ */
159
+ function expressLogger(options = {}) {
160
+ const category = normalizeCategory(options.category ?? ["express"]);
161
+ const logger = (0, __logtape_logtape.getLogger)(category);
162
+ const level = options.level ?? "info";
163
+ const formatOption = options.format ?? "combined";
164
+ const skip = options.skip ?? (() => false);
165
+ const immediate = options.immediate ?? false;
166
+ const formatFn = typeof formatOption === "string" ? predefinedFormats[formatOption] : formatOption;
167
+ const logMethod = logger[level].bind(logger);
168
+ return (req, res, next) => {
169
+ const startTime = Date.now();
170
+ if (immediate) {
171
+ if (!skip(req, res)) {
172
+ const result = formatFn(req, res, 0);
173
+ if (typeof result === "string") logMethod(result);
174
+ else logMethod("{method} {url}", result);
175
+ }
176
+ next();
177
+ return;
178
+ }
179
+ const logRequest = () => {
180
+ if (skip(req, res)) return;
181
+ const responseTime = Date.now() - startTime;
182
+ const result = formatFn(req, res, responseTime);
183
+ if (typeof result === "string") logMethod(result);
184
+ else logMethod("{method} {url} {status} - {responseTime} ms", result);
185
+ };
186
+ res.on("finish", logRequest);
187
+ next();
188
+ };
189
+ }
190
+
191
+ //#endregion
192
+ exports.expressLogger = expressLogger;
package/dist/mod.d.cts ADDED
@@ -0,0 +1,192 @@
1
+ import { LogLevel, LogLevel as LogLevel$1 } from "@logtape/logtape";
2
+
3
+ //#region src/mod.d.ts
4
+
5
+ /**
6
+ * Minimal Express Request interface for compatibility.
7
+ * @since 1.3.0
8
+ */
9
+ interface ExpressRequest {
10
+ method: string;
11
+ url: string;
12
+ originalUrl?: string;
13
+ path?: string;
14
+ httpVersion: string;
15
+ ip?: string;
16
+ socket?: {
17
+ remoteAddress?: string;
18
+ };
19
+ get(header: string): string | undefined;
20
+ }
21
+ /**
22
+ * Minimal Express Response interface for compatibility.
23
+ * @since 1.3.0
24
+ */
25
+ interface ExpressResponse {
26
+ statusCode: number;
27
+ on(event: string, listener: () => void): void;
28
+ getHeader(name: string): string | number | string[] | undefined;
29
+ }
30
+ /**
31
+ * Express NextFunction type.
32
+ * @since 1.3.0
33
+ */
34
+ type ExpressNextFunction = (err?: unknown) => void;
35
+ /**
36
+ * Express middleware function type.
37
+ * @since 1.3.0
38
+ */
39
+ type ExpressMiddleware = (req: ExpressRequest, res: ExpressResponse, next: ExpressNextFunction) => void;
40
+ /**
41
+ * Predefined log format names compatible with Morgan.
42
+ * @since 1.3.0
43
+ */
44
+ type PredefinedFormat = "combined" | "common" | "dev" | "short" | "tiny";
45
+ /**
46
+ * Custom format function for request logging.
47
+ *
48
+ * @param req The Express request object.
49
+ * @param res The Express response object.
50
+ * @param responseTime The response time in milliseconds.
51
+ * @returns A string message or an object with structured properties.
52
+ * @since 1.3.0
53
+ */
54
+ type FormatFunction = (req: ExpressRequest, res: ExpressResponse, responseTime: number) => string | Record<string, unknown>;
55
+ /**
56
+ * Structured log properties for HTTP requests.
57
+ * @since 1.3.0
58
+ */
59
+ interface RequestLogProperties {
60
+ /** HTTP request method */
61
+ method: string;
62
+ /** Request URL */
63
+ url: string;
64
+ /** HTTP response status code */
65
+ status: number;
66
+ /** Response time in milliseconds */
67
+ responseTime: number;
68
+ /** Response content-length header value */
69
+ contentLength: string | undefined;
70
+ /** Remote client address */
71
+ remoteAddr: string | undefined;
72
+ /** User-Agent header value */
73
+ userAgent: string | undefined;
74
+ /** Referrer header value */
75
+ referrer: string | undefined;
76
+ /** HTTP version (e.g., "1.1") */
77
+ httpVersion: string;
78
+ }
79
+ /**
80
+ * Options for configuring the Express LogTape middleware.
81
+ * @since 1.3.0
82
+ */
83
+ interface ExpressLogTapeOptions {
84
+ /**
85
+ * The LogTape category to use for logging.
86
+ * @default ["express"]
87
+ */
88
+ readonly category?: string | readonly string[];
89
+ /**
90
+ * The log level to use for request logging.
91
+ * @default "info"
92
+ */
93
+ readonly level?: LogLevel$1;
94
+ /**
95
+ * The format for log output.
96
+ * Can be a predefined format name or a custom format function.
97
+ *
98
+ * Predefined formats:
99
+ * - `"combined"` - Apache Combined Log Format (structured, default)
100
+ * - `"common"` - Apache Common Log Format (structured, no referrer/userAgent)
101
+ * - `"dev"` - Concise colored output for development (string)
102
+ * - `"short"` - Shorter than common (string)
103
+ * - `"tiny"` - Minimal output (string)
104
+ *
105
+ * @default "combined"
106
+ */
107
+ readonly format?: PredefinedFormat | FormatFunction;
108
+ /**
109
+ * Function to determine whether logging should be skipped.
110
+ * Return `true` to skip logging for a request.
111
+ *
112
+ * @example Skip logging for successful requests
113
+ * ```typescript
114
+ * app.use(expressLogger({
115
+ * skip: (req, res) => res.statusCode < 400,
116
+ * }));
117
+ * ```
118
+ *
119
+ * @default () => false
120
+ */
121
+ readonly skip?: (req: ExpressRequest, res: ExpressResponse) => boolean;
122
+ /**
123
+ * If `true`, logs are written immediately when the request is received.
124
+ * If `false` (default), logs are written after the response is sent.
125
+ *
126
+ * Note: When `immediate` is `true`, response-related properties
127
+ * (status, responseTime, contentLength) will not be available.
128
+ *
129
+ * @default false
130
+ */
131
+ readonly immediate?: boolean;
132
+ }
133
+ /**
134
+ * Creates Express middleware for HTTP request logging using LogTape.
135
+ *
136
+ * This middleware provides Morgan-compatible request logging with LogTape
137
+ * as the backend, supporting structured logging and customizable formats.
138
+ *
139
+ * @example Basic usage
140
+ * ```typescript
141
+ * import express from "express";
142
+ * import { configure, getConsoleSink } from "@logtape/logtape";
143
+ * import { expressLogger } from "@logtape/express";
144
+ *
145
+ * await configure({
146
+ * sinks: { console: getConsoleSink() },
147
+ * loggers: [
148
+ * { category: ["express"], sinks: ["console"], lowestLevel: "info" }
149
+ * ],
150
+ * });
151
+ *
152
+ * const app = express();
153
+ * app.use(expressLogger());
154
+ *
155
+ * app.get("/", (req, res) => {
156
+ * res.json({ hello: "world" });
157
+ * });
158
+ *
159
+ * app.listen(3000);
160
+ * ```
161
+ *
162
+ * @example With custom options
163
+ * ```typescript
164
+ * app.use(expressLogger({
165
+ * category: ["myapp", "http"],
166
+ * level: "debug",
167
+ * format: "dev",
168
+ * skip: (req, res) => res.statusCode < 400,
169
+ * }));
170
+ * ```
171
+ *
172
+ * @example With custom format function
173
+ * ```typescript
174
+ * app.use(expressLogger({
175
+ * format: (req, res, responseTime) => ({
176
+ * method: req.method,
177
+ * path: req.path,
178
+ * status: res.statusCode,
179
+ * duration: responseTime,
180
+ * }),
181
+ * }));
182
+ * ```
183
+ *
184
+ * @param options Configuration options for the middleware.
185
+ * @returns Express middleware function.
186
+ * @since 1.3.0
187
+ */
188
+ declare function expressLogger(options?: ExpressLogTapeOptions): ExpressMiddleware;
189
+ //# sourceMappingURL=mod.d.ts.map
190
+ //#endregion
191
+ export { ExpressLogTapeOptions, ExpressMiddleware, ExpressNextFunction, ExpressRequest, ExpressResponse, FormatFunction, LogLevel, PredefinedFormat, RequestLogProperties, expressLogger };
192
+ //# sourceMappingURL=mod.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.d.cts","names":[],"sources":["../src/mod.ts"],"sourcesContent":[],"mappings":";;;;;AAWA;AAeA;AAUA;AAMY,UA/BK,cAAA,CA+BY;EAAA,MAAA,EAAA,MAAA;EAAA,GACtB,EAAA,MAAA;EAAc,WACd,CAAA,EAAA,MAAA;EAAe,IACd,CAAA,EAAA,MAAA;EAAmB,WAAA,EAAA,MAAA;EAOf,EAAA,CAAA,EAAA,MAAA;EAWA,MAAA,CAAA,EAAA;IAAc,aAAA,CAAA,EAAA,MAAA;EAAA,CAAA;EACL,GACd,CAAA,MAAA,EAAA,MAAA,CAAA,EAAA,MAAA,GAAA,SAAA;;AAEa;AAMpB;AAyBA;;AAWmB,UAnFF,eAAA,CAmFE;EAAQ,UAeP,EAAA,MAAA;EAAgB,EAAA,CAAG,KAAA,EAAA,MAAA,EAAA,QAAA,EAAA,GAAA,GAAA,IAAA,CAAA,EAAA,IAAA;EAAc,SAe7B,CAAA,IAAA,EAAA,MAAA,CAAA,EAAA,MAAA,GAAA,MAAA,GAAA,MAAA,EAAA,GAAA,SAAA;;AAAoC;AAsN5D;;;AAEG,KA/TS,mBAAA,GA+TT,CAAA,GAAA,CAAA,EAAA,OAAA,EAAA,GAAA,IAAA;AAAiB;;;;KAzTR,iBAAA,SACL,qBACA,uBACC;;;;;KAOI,gBAAA;;;;;;;;;;KAWA,cAAA,SACL,qBACA,mDAEO;;;;;UAMG,oBAAA;;;;;;;;;;;;;;;;;;;;;;;;UAyBA,qBAAA;;;;;;;;;;mBAWE;;;;;;;;;;;;;;oBAeC,mBAAmB;;;;;;;;;;;;;;wBAef,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsN7B,aAAA,WACL,wBACR"}