@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/dist/mod.d.ts 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.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.d.ts","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"}
package/dist/mod.js ADDED
@@ -0,0 +1,192 @@
1
+ import { getLogger } from "@logtape/logtape";
2
+
3
+ //#region src/mod.ts
4
+ /**
5
+ * Get remote address from request.
6
+ */
7
+ function getRemoteAddr(req) {
8
+ return req.ip || req.socket?.remoteAddress;
9
+ }
10
+ /**
11
+ * Get content length from response headers.
12
+ */
13
+ function getContentLength(res) {
14
+ const contentLength = res.getHeader("content-length");
15
+ if (contentLength === void 0 || contentLength === null) return void 0;
16
+ return String(contentLength);
17
+ }
18
+ /**
19
+ * Get referrer from request headers.
20
+ */
21
+ function getReferrer(req) {
22
+ return req.get("referrer") || req.get("referer");
23
+ }
24
+ /**
25
+ * Get user agent from request headers.
26
+ */
27
+ function getUserAgent(req) {
28
+ return req.get("user-agent");
29
+ }
30
+ /**
31
+ * Build structured log properties from request/response.
32
+ */
33
+ function buildProperties(req, res, responseTime) {
34
+ return {
35
+ method: req.method,
36
+ url: req.originalUrl || req.url,
37
+ status: res.statusCode,
38
+ responseTime,
39
+ contentLength: getContentLength(res),
40
+ remoteAddr: getRemoteAddr(req),
41
+ userAgent: getUserAgent(req),
42
+ referrer: getReferrer(req),
43
+ httpVersion: req.httpVersion
44
+ };
45
+ }
46
+ /**
47
+ * Combined format (Apache Combined Log Format).
48
+ * Returns all structured properties.
49
+ */
50
+ function formatCombined(req, res, responseTime) {
51
+ return { ...buildProperties(req, res, responseTime) };
52
+ }
53
+ /**
54
+ * Common format (Apache Common Log Format).
55
+ * Like combined but without referrer and userAgent.
56
+ */
57
+ function formatCommon(req, res, responseTime) {
58
+ const props = buildProperties(req, res, responseTime);
59
+ const { referrer: _referrer, userAgent: _userAgent,...rest } = props;
60
+ return rest;
61
+ }
62
+ /**
63
+ * Dev format (colored output for development).
64
+ * :method :url :status :response-time ms - :res[content-length]
65
+ */
66
+ function formatDev(req, res, responseTime) {
67
+ const contentLength = getContentLength(res) ?? "-";
68
+ return `${req.method} ${req.originalUrl || req.url} ${res.statusCode} ${responseTime.toFixed(3)} ms - ${contentLength}`;
69
+ }
70
+ /**
71
+ * Short format.
72
+ * :remote-addr :method :url HTTP/:http-version :status :res[content-length] - :response-time ms
73
+ */
74
+ function formatShort(req, res, responseTime) {
75
+ const remoteAddr = getRemoteAddr(req) ?? "-";
76
+ const contentLength = getContentLength(res) ?? "-";
77
+ return `${remoteAddr} ${req.method} ${req.originalUrl || req.url} HTTP/${req.httpVersion} ${res.statusCode} ${contentLength} - ${responseTime.toFixed(3)} ms`;
78
+ }
79
+ /**
80
+ * Tiny format (minimal output).
81
+ * :method :url :status :res[content-length] - :response-time ms
82
+ */
83
+ function formatTiny(req, res, responseTime) {
84
+ const contentLength = getContentLength(res) ?? "-";
85
+ return `${req.method} ${req.originalUrl || req.url} ${res.statusCode} ${contentLength} - ${responseTime.toFixed(3)} ms`;
86
+ }
87
+ /**
88
+ * Map of predefined format functions.
89
+ */
90
+ const predefinedFormats = {
91
+ combined: formatCombined,
92
+ common: formatCommon,
93
+ dev: formatDev,
94
+ short: formatShort,
95
+ tiny: formatTiny
96
+ };
97
+ /**
98
+ * Normalize category to array format.
99
+ */
100
+ function normalizeCategory(category) {
101
+ return typeof category === "string" ? [category] : category;
102
+ }
103
+ /**
104
+ * Creates Express middleware for HTTP request logging using LogTape.
105
+ *
106
+ * This middleware provides Morgan-compatible request logging with LogTape
107
+ * as the backend, supporting structured logging and customizable formats.
108
+ *
109
+ * @example Basic usage
110
+ * ```typescript
111
+ * import express from "express";
112
+ * import { configure, getConsoleSink } from "@logtape/logtape";
113
+ * import { expressLogger } from "@logtape/express";
114
+ *
115
+ * await configure({
116
+ * sinks: { console: getConsoleSink() },
117
+ * loggers: [
118
+ * { category: ["express"], sinks: ["console"], lowestLevel: "info" }
119
+ * ],
120
+ * });
121
+ *
122
+ * const app = express();
123
+ * app.use(expressLogger());
124
+ *
125
+ * app.get("/", (req, res) => {
126
+ * res.json({ hello: "world" });
127
+ * });
128
+ *
129
+ * app.listen(3000);
130
+ * ```
131
+ *
132
+ * @example With custom options
133
+ * ```typescript
134
+ * app.use(expressLogger({
135
+ * category: ["myapp", "http"],
136
+ * level: "debug",
137
+ * format: "dev",
138
+ * skip: (req, res) => res.statusCode < 400,
139
+ * }));
140
+ * ```
141
+ *
142
+ * @example With custom format function
143
+ * ```typescript
144
+ * app.use(expressLogger({
145
+ * format: (req, res, responseTime) => ({
146
+ * method: req.method,
147
+ * path: req.path,
148
+ * status: res.statusCode,
149
+ * duration: responseTime,
150
+ * }),
151
+ * }));
152
+ * ```
153
+ *
154
+ * @param options Configuration options for the middleware.
155
+ * @returns Express middleware function.
156
+ * @since 1.3.0
157
+ */
158
+ function expressLogger(options = {}) {
159
+ const category = normalizeCategory(options.category ?? ["express"]);
160
+ const logger = getLogger(category);
161
+ const level = options.level ?? "info";
162
+ const formatOption = options.format ?? "combined";
163
+ const skip = options.skip ?? (() => false);
164
+ const immediate = options.immediate ?? false;
165
+ const formatFn = typeof formatOption === "string" ? predefinedFormats[formatOption] : formatOption;
166
+ const logMethod = logger[level].bind(logger);
167
+ return (req, res, next) => {
168
+ const startTime = Date.now();
169
+ if (immediate) {
170
+ if (!skip(req, res)) {
171
+ const result = formatFn(req, res, 0);
172
+ if (typeof result === "string") logMethod(result);
173
+ else logMethod("{method} {url}", result);
174
+ }
175
+ next();
176
+ return;
177
+ }
178
+ const logRequest = () => {
179
+ if (skip(req, res)) return;
180
+ const responseTime = Date.now() - startTime;
181
+ const result = formatFn(req, res, responseTime);
182
+ if (typeof result === "string") logMethod(result);
183
+ else logMethod("{method} {url} {status} - {responseTime} ms", result);
184
+ };
185
+ res.on("finish", logRequest);
186
+ next();
187
+ };
188
+ }
189
+
190
+ //#endregion
191
+ export { expressLogger };
192
+ //# sourceMappingURL=mod.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.js","names":["req: ExpressRequest","res: ExpressResponse","responseTime: number","predefinedFormats: Record<PredefinedFormat, FormatFunction>","category: string | readonly string[]","options: ExpressLogTapeOptions","formatFn: FormatFunction","next: ExpressNextFunction"],"sources":["../src/mod.ts"],"sourcesContent":["import { getLogger, type LogLevel } from \"@logtape/logtape\";\n\nexport type { LogLevel } from \"@logtape/logtape\";\n\n// Use minimal type definitions for Express compatibility across Express 4.x and 5.x\n// These are compatible with both versions and avoid strict type checking issues\n\n/**\n * Minimal Express Request interface for compatibility.\n * @since 1.3.0\n */\nexport interface ExpressRequest {\n method: string;\n url: string;\n originalUrl?: string;\n path?: string;\n httpVersion: string;\n ip?: string;\n socket?: { remoteAddress?: string };\n get(header: string): string | undefined;\n}\n\n/**\n * Minimal Express Response interface for compatibility.\n * @since 1.3.0\n */\nexport interface ExpressResponse {\n statusCode: number;\n on(event: string, listener: () => void): void;\n getHeader(name: string): string | number | string[] | undefined;\n}\n\n/**\n * Express NextFunction type.\n * @since 1.3.0\n */\nexport type ExpressNextFunction = (err?: unknown) => void;\n\n/**\n * Express middleware function type.\n * @since 1.3.0\n */\nexport type ExpressMiddleware = (\n req: ExpressRequest,\n res: ExpressResponse,\n next: ExpressNextFunction,\n) => void;\n\n/**\n * Predefined log format names compatible with Morgan.\n * @since 1.3.0\n */\nexport type PredefinedFormat = \"combined\" | \"common\" | \"dev\" | \"short\" | \"tiny\";\n\n/**\n * Custom format function for request logging.\n *\n * @param req The Express request object.\n * @param res The Express response object.\n * @param responseTime The response time in milliseconds.\n * @returns A string message or an object with structured properties.\n * @since 1.3.0\n */\nexport type FormatFunction = (\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n) => string | Record<string, unknown>;\n\n/**\n * Structured log properties for HTTP requests.\n * @since 1.3.0\n */\nexport interface RequestLogProperties {\n /** HTTP request method */\n method: string;\n /** Request URL */\n url: 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 */\n remoteAddr: string | undefined;\n /** User-Agent header value */\n userAgent: string | undefined;\n /** Referrer header value */\n referrer: string | undefined;\n /** HTTP version (e.g., \"1.1\") */\n httpVersion: string;\n}\n\n/**\n * Options for configuring the Express LogTape middleware.\n * @since 1.3.0\n */\nexport interface ExpressLogTapeOptions {\n /**\n * The LogTape category to use for logging.\n * @default [\"express\"]\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 successful requests\n * ```typescript\n * app.use(expressLogger({\n * skip: (req, res) => res.statusCode < 400,\n * }));\n * ```\n *\n * @default () => false\n */\n readonly skip?: (req: ExpressRequest, res: ExpressResponse) => 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 `immediate` is `true`, response-related properties\n * (status, responseTime, contentLength) will not be available.\n *\n * @default false\n */\n readonly immediate?: boolean;\n}\n\n/**\n * Get remote address from request.\n */\nfunction getRemoteAddr(req: ExpressRequest): string | undefined {\n return req.ip || req.socket?.remoteAddress;\n}\n\n/**\n * Get content length from response headers.\n */\nfunction getContentLength(res: ExpressResponse): string | undefined {\n const contentLength = res.getHeader(\"content-length\");\n if (contentLength === undefined || contentLength === null) return undefined;\n return String(contentLength);\n}\n\n/**\n * Get referrer from request headers.\n */\nfunction getReferrer(req: ExpressRequest): string | undefined {\n return req.get(\"referrer\") || req.get(\"referer\");\n}\n\n/**\n * Get user agent from request headers.\n */\nfunction getUserAgent(req: ExpressRequest): string | undefined {\n return req.get(\"user-agent\");\n}\n\n/**\n * Build structured log properties from request/response.\n */\nfunction buildProperties(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): RequestLogProperties {\n return {\n method: req.method,\n url: req.originalUrl || req.url,\n status: res.statusCode,\n responseTime,\n contentLength: getContentLength(res),\n remoteAddr: getRemoteAddr(req),\n userAgent: getUserAgent(req),\n referrer: getReferrer(req),\n httpVersion: req.httpVersion,\n };\n}\n\n/**\n * Combined format (Apache Combined Log Format).\n * Returns all structured properties.\n */\nfunction formatCombined(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): Record<string, unknown> {\n return { ...buildProperties(req, res, responseTime) };\n}\n\n/**\n * Common format (Apache Common Log Format).\n * Like combined but without referrer and userAgent.\n */\nfunction formatCommon(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): Record<string, unknown> {\n const props = buildProperties(req, res, responseTime);\n const { referrer: _referrer, userAgent: _userAgent, ...rest } = props;\n return rest;\n}\n\n/**\n * Dev format (colored output for development).\n * :method :url :status :response-time ms - :res[content-length]\n */\nfunction formatDev(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): string {\n const contentLength = getContentLength(res) ?? \"-\";\n return `${req.method} ${req.originalUrl || req.url} ${res.statusCode} ${\n responseTime.toFixed(3)\n } ms - ${contentLength}`;\n}\n\n/**\n * Short format.\n * :remote-addr :method :url HTTP/:http-version :status :res[content-length] - :response-time ms\n */\nfunction formatShort(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): string {\n const remoteAddr = getRemoteAddr(req) ?? \"-\";\n const contentLength = getContentLength(res) ?? \"-\";\n return `${remoteAddr} ${req.method} ${\n req.originalUrl || req.url\n } HTTP/${req.httpVersion} ${res.statusCode} ${contentLength} - ${\n responseTime.toFixed(3)\n } ms`;\n}\n\n/**\n * Tiny format (minimal output).\n * :method :url :status :res[content-length] - :response-time ms\n */\nfunction formatTiny(\n req: ExpressRequest,\n res: ExpressResponse,\n responseTime: number,\n): string {\n const contentLength = getContentLength(res) ?? \"-\";\n return `${req.method} ${\n req.originalUrl || req.url\n } ${res.statusCode} ${contentLength} - ${responseTime.toFixed(3)} 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 * Creates Express middleware for HTTP request logging using LogTape.\n *\n * This middleware 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 express from \"express\";\n * import { configure, getConsoleSink } from \"@logtape/logtape\";\n * import { expressLogger } from \"@logtape/express\";\n *\n * await configure({\n * sinks: { console: getConsoleSink() },\n * loggers: [\n * { category: [\"express\"], sinks: [\"console\"], lowestLevel: \"info\" }\n * ],\n * });\n *\n * const app = express();\n * app.use(expressLogger());\n *\n * app.get(\"/\", (req, res) => {\n * res.json({ hello: \"world\" });\n * });\n *\n * app.listen(3000);\n * ```\n *\n * @example With custom options\n * ```typescript\n * app.use(expressLogger({\n * category: [\"myapp\", \"http\"],\n * level: \"debug\",\n * format: \"dev\",\n * skip: (req, res) => res.statusCode < 400,\n * }));\n * ```\n *\n * @example With custom format function\n * ```typescript\n * app.use(expressLogger({\n * format: (req, res, responseTime) => ({\n * method: req.method,\n * path: req.path,\n * status: res.statusCode,\n * duration: responseTime,\n * }),\n * }));\n * ```\n *\n * @param options Configuration options for the middleware.\n * @returns Express middleware function.\n * @since 1.3.0\n */\nexport function expressLogger(\n options: ExpressLogTapeOptions = {},\n): ExpressMiddleware {\n const category = normalizeCategory(options.category ?? [\"express\"]);\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 immediate = options.immediate ?? false;\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\n return (\n req: ExpressRequest,\n res: ExpressResponse,\n next: ExpressNextFunction,\n ): void => {\n const startTime = Date.now();\n\n // For immediate logging, log when request arrives\n if (immediate) {\n if (!skip(req, res)) {\n const result = formatFn(req, res, 0);\n if (typeof result === \"string\") {\n logMethod(result);\n } else {\n logMethod(\"{method} {url}\", result);\n }\n }\n next();\n return;\n }\n\n // Log after response is sent\n const logRequest = (): void => {\n if (skip(req, res)) return;\n\n const responseTime = Date.now() - startTime;\n const result = formatFn(req, res, responseTime);\n\n if (typeof result === \"string\") {\n logMethod(result);\n } else {\n logMethod(\"{method} {url} {status} - {responseTime} ms\", result);\n }\n };\n\n // Listen for response finish event\n res.on(\"finish\", logRequest);\n\n next();\n };\n}\n"],"mappings":"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"}
package/package.json ADDED
@@ -0,0 +1,71 @@
1
+ {
2
+ "name": "@logtape/express",
3
+ "version": "1.3.0-dev.1",
4
+ "description": "Express adapter for LogTape logging library",
5
+ "keywords": [
6
+ "logging",
7
+ "log",
8
+ "logger",
9
+ "express",
10
+ "middleware",
11
+ "morgan",
12
+ "http",
13
+ "request",
14
+ "adapter",
15
+ "logtape"
16
+ ],
17
+ "license": "MIT",
18
+ "author": {
19
+ "name": "Hong Minhee",
20
+ "email": "hong@minhee.org",
21
+ "url": "https://hongminhee.org/"
22
+ },
23
+ "homepage": "https://logtape.org/",
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/dahlia/logtape.git",
27
+ "directory": "packages/express/"
28
+ },
29
+ "bugs": {
30
+ "url": "https://github.com/dahlia/logtape/issues"
31
+ },
32
+ "funding": [
33
+ "https://github.com/sponsors/dahlia"
34
+ ],
35
+ "type": "module",
36
+ "module": "./dist/mod.js",
37
+ "main": "./dist/mod.cjs",
38
+ "types": "./dist/mod.d.ts",
39
+ "exports": {
40
+ ".": {
41
+ "types": {
42
+ "import": "./dist/mod.d.ts",
43
+ "require": "./dist/mod.d.cts"
44
+ },
45
+ "import": "./dist/mod.js",
46
+ "require": "./dist/mod.cjs"
47
+ },
48
+ "./package.json": "./package.json"
49
+ },
50
+ "sideEffects": false,
51
+ "peerDependencies": {
52
+ "express": "^4.0.0 || ^5.0.0",
53
+ "@logtape/logtape": "^1.3.0"
54
+ },
55
+ "devDependencies": {
56
+ "@alinea/suite": "^0.6.3",
57
+ "@std/assert": "npm:@jsr/std__assert@^1.0.13",
58
+ "@types/express": "^5.0.6",
59
+ "express": "^5.2.1",
60
+ "tsdown": "^0.12.7",
61
+ "typescript": "^5.8.3"
62
+ },
63
+ "scripts": {
64
+ "build": "tsdown",
65
+ "prepublish": "tsdown",
66
+ "test": "tsdown && node --experimental-transform-types --test",
67
+ "test:bun": "tsdown && bun test",
68
+ "test:deno": "deno test --allow-env --allow-sys --allow-net",
69
+ "test-all": "tsdown && node --experimental-transform-types --test && bun test && deno test"
70
+ }
71
+ }