@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 +20 -0
- package/README.md +104 -0
- package/deno.json +34 -0
- package/dist/_virtual/rolldown_runtime.cjs +30 -0
- package/dist/mod.cjs +192 -0
- package/dist/mod.d.cts +192 -0
- package/dist/mod.d.cts.map +1 -0
- package/dist/mod.d.ts +192 -0
- package/dist/mod.d.ts.map +1 -0
- package/dist/mod.js +192 -0
- package/dist/mod.js.map +1 -0
- package/package.json +71 -0
- package/src/mod.test.ts +875 -0
- package/src/mod.ts +411 -0
- package/tsdown.config.ts +11 -0
package/src/mod.ts
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
import { getLogger, type LogLevel } from "@logtape/logtape";
|
|
2
|
+
|
|
3
|
+
export type { LogLevel } from "@logtape/logtape";
|
|
4
|
+
|
|
5
|
+
// Use minimal type definitions for Express compatibility across Express 4.x and 5.x
|
|
6
|
+
// These are compatible with both versions and avoid strict type checking issues
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Minimal Express Request interface for compatibility.
|
|
10
|
+
* @since 1.3.0
|
|
11
|
+
*/
|
|
12
|
+
export interface ExpressRequest {
|
|
13
|
+
method: string;
|
|
14
|
+
url: string;
|
|
15
|
+
originalUrl?: string;
|
|
16
|
+
path?: string;
|
|
17
|
+
httpVersion: string;
|
|
18
|
+
ip?: string;
|
|
19
|
+
socket?: { remoteAddress?: string };
|
|
20
|
+
get(header: string): string | undefined;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Minimal Express Response interface for compatibility.
|
|
25
|
+
* @since 1.3.0
|
|
26
|
+
*/
|
|
27
|
+
export interface ExpressResponse {
|
|
28
|
+
statusCode: number;
|
|
29
|
+
on(event: string, listener: () => void): void;
|
|
30
|
+
getHeader(name: string): string | number | string[] | undefined;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Express NextFunction type.
|
|
35
|
+
* @since 1.3.0
|
|
36
|
+
*/
|
|
37
|
+
export type ExpressNextFunction = (err?: unknown) => void;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Express middleware function type.
|
|
41
|
+
* @since 1.3.0
|
|
42
|
+
*/
|
|
43
|
+
export type ExpressMiddleware = (
|
|
44
|
+
req: ExpressRequest,
|
|
45
|
+
res: ExpressResponse,
|
|
46
|
+
next: ExpressNextFunction,
|
|
47
|
+
) => void;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Predefined log format names compatible with Morgan.
|
|
51
|
+
* @since 1.3.0
|
|
52
|
+
*/
|
|
53
|
+
export type PredefinedFormat = "combined" | "common" | "dev" | "short" | "tiny";
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Custom format function for request logging.
|
|
57
|
+
*
|
|
58
|
+
* @param req The Express request object.
|
|
59
|
+
* @param res The Express response object.
|
|
60
|
+
* @param responseTime The response time in milliseconds.
|
|
61
|
+
* @returns A string message or an object with structured properties.
|
|
62
|
+
* @since 1.3.0
|
|
63
|
+
*/
|
|
64
|
+
export type FormatFunction = (
|
|
65
|
+
req: ExpressRequest,
|
|
66
|
+
res: ExpressResponse,
|
|
67
|
+
responseTime: number,
|
|
68
|
+
) => string | Record<string, unknown>;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Structured log properties for HTTP requests.
|
|
72
|
+
* @since 1.3.0
|
|
73
|
+
*/
|
|
74
|
+
export interface RequestLogProperties {
|
|
75
|
+
/** HTTP request method */
|
|
76
|
+
method: string;
|
|
77
|
+
/** Request URL */
|
|
78
|
+
url: string;
|
|
79
|
+
/** HTTP response status code */
|
|
80
|
+
status: number;
|
|
81
|
+
/** Response time in milliseconds */
|
|
82
|
+
responseTime: number;
|
|
83
|
+
/** Response content-length header value */
|
|
84
|
+
contentLength: string | undefined;
|
|
85
|
+
/** Remote client address */
|
|
86
|
+
remoteAddr: string | undefined;
|
|
87
|
+
/** User-Agent header value */
|
|
88
|
+
userAgent: string | undefined;
|
|
89
|
+
/** Referrer header value */
|
|
90
|
+
referrer: string | undefined;
|
|
91
|
+
/** HTTP version (e.g., "1.1") */
|
|
92
|
+
httpVersion: string;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Options for configuring the Express LogTape middleware.
|
|
97
|
+
* @since 1.3.0
|
|
98
|
+
*/
|
|
99
|
+
export interface ExpressLogTapeOptions {
|
|
100
|
+
/**
|
|
101
|
+
* The LogTape category to use for logging.
|
|
102
|
+
* @default ["express"]
|
|
103
|
+
*/
|
|
104
|
+
readonly category?: string | readonly string[];
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* The log level to use for request logging.
|
|
108
|
+
* @default "info"
|
|
109
|
+
*/
|
|
110
|
+
readonly level?: LogLevel;
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* The format for log output.
|
|
114
|
+
* Can be a predefined format name or a custom format function.
|
|
115
|
+
*
|
|
116
|
+
* Predefined formats:
|
|
117
|
+
* - `"combined"` - Apache Combined Log Format (structured, default)
|
|
118
|
+
* - `"common"` - Apache Common Log Format (structured, no referrer/userAgent)
|
|
119
|
+
* - `"dev"` - Concise colored output for development (string)
|
|
120
|
+
* - `"short"` - Shorter than common (string)
|
|
121
|
+
* - `"tiny"` - Minimal output (string)
|
|
122
|
+
*
|
|
123
|
+
* @default "combined"
|
|
124
|
+
*/
|
|
125
|
+
readonly format?: PredefinedFormat | FormatFunction;
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Function to determine whether logging should be skipped.
|
|
129
|
+
* Return `true` to skip logging for a request.
|
|
130
|
+
*
|
|
131
|
+
* @example Skip logging for successful requests
|
|
132
|
+
* ```typescript
|
|
133
|
+
* app.use(expressLogger({
|
|
134
|
+
* skip: (req, res) => res.statusCode < 400,
|
|
135
|
+
* }));
|
|
136
|
+
* ```
|
|
137
|
+
*
|
|
138
|
+
* @default () => false
|
|
139
|
+
*/
|
|
140
|
+
readonly skip?: (req: ExpressRequest, res: ExpressResponse) => boolean;
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* If `true`, logs are written immediately when the request is received.
|
|
144
|
+
* If `false` (default), logs are written after the response is sent.
|
|
145
|
+
*
|
|
146
|
+
* Note: When `immediate` is `true`, response-related properties
|
|
147
|
+
* (status, responseTime, contentLength) will not be available.
|
|
148
|
+
*
|
|
149
|
+
* @default false
|
|
150
|
+
*/
|
|
151
|
+
readonly immediate?: boolean;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Get remote address from request.
|
|
156
|
+
*/
|
|
157
|
+
function getRemoteAddr(req: ExpressRequest): string | undefined {
|
|
158
|
+
return req.ip || req.socket?.remoteAddress;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Get content length from response headers.
|
|
163
|
+
*/
|
|
164
|
+
function getContentLength(res: ExpressResponse): string | undefined {
|
|
165
|
+
const contentLength = res.getHeader("content-length");
|
|
166
|
+
if (contentLength === undefined || contentLength === null) return undefined;
|
|
167
|
+
return String(contentLength);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Get referrer from request headers.
|
|
172
|
+
*/
|
|
173
|
+
function getReferrer(req: ExpressRequest): string | undefined {
|
|
174
|
+
return req.get("referrer") || req.get("referer");
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Get user agent from request headers.
|
|
179
|
+
*/
|
|
180
|
+
function getUserAgent(req: ExpressRequest): string | undefined {
|
|
181
|
+
return req.get("user-agent");
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Build structured log properties from request/response.
|
|
186
|
+
*/
|
|
187
|
+
function buildProperties(
|
|
188
|
+
req: ExpressRequest,
|
|
189
|
+
res: ExpressResponse,
|
|
190
|
+
responseTime: number,
|
|
191
|
+
): RequestLogProperties {
|
|
192
|
+
return {
|
|
193
|
+
method: req.method,
|
|
194
|
+
url: req.originalUrl || req.url,
|
|
195
|
+
status: res.statusCode,
|
|
196
|
+
responseTime,
|
|
197
|
+
contentLength: getContentLength(res),
|
|
198
|
+
remoteAddr: getRemoteAddr(req),
|
|
199
|
+
userAgent: getUserAgent(req),
|
|
200
|
+
referrer: getReferrer(req),
|
|
201
|
+
httpVersion: req.httpVersion,
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Combined format (Apache Combined Log Format).
|
|
207
|
+
* Returns all structured properties.
|
|
208
|
+
*/
|
|
209
|
+
function formatCombined(
|
|
210
|
+
req: ExpressRequest,
|
|
211
|
+
res: ExpressResponse,
|
|
212
|
+
responseTime: number,
|
|
213
|
+
): Record<string, unknown> {
|
|
214
|
+
return { ...buildProperties(req, res, responseTime) };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Common format (Apache Common Log Format).
|
|
219
|
+
* Like combined but without referrer and userAgent.
|
|
220
|
+
*/
|
|
221
|
+
function formatCommon(
|
|
222
|
+
req: ExpressRequest,
|
|
223
|
+
res: ExpressResponse,
|
|
224
|
+
responseTime: number,
|
|
225
|
+
): Record<string, unknown> {
|
|
226
|
+
const props = buildProperties(req, res, responseTime);
|
|
227
|
+
const { referrer: _referrer, userAgent: _userAgent, ...rest } = props;
|
|
228
|
+
return rest;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Dev format (colored output for development).
|
|
233
|
+
* :method :url :status :response-time ms - :res[content-length]
|
|
234
|
+
*/
|
|
235
|
+
function formatDev(
|
|
236
|
+
req: ExpressRequest,
|
|
237
|
+
res: ExpressResponse,
|
|
238
|
+
responseTime: number,
|
|
239
|
+
): string {
|
|
240
|
+
const contentLength = getContentLength(res) ?? "-";
|
|
241
|
+
return `${req.method} ${req.originalUrl || req.url} ${res.statusCode} ${
|
|
242
|
+
responseTime.toFixed(3)
|
|
243
|
+
} ms - ${contentLength}`;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Short format.
|
|
248
|
+
* :remote-addr :method :url HTTP/:http-version :status :res[content-length] - :response-time ms
|
|
249
|
+
*/
|
|
250
|
+
function formatShort(
|
|
251
|
+
req: ExpressRequest,
|
|
252
|
+
res: ExpressResponse,
|
|
253
|
+
responseTime: number,
|
|
254
|
+
): string {
|
|
255
|
+
const remoteAddr = getRemoteAddr(req) ?? "-";
|
|
256
|
+
const contentLength = getContentLength(res) ?? "-";
|
|
257
|
+
return `${remoteAddr} ${req.method} ${
|
|
258
|
+
req.originalUrl || req.url
|
|
259
|
+
} HTTP/${req.httpVersion} ${res.statusCode} ${contentLength} - ${
|
|
260
|
+
responseTime.toFixed(3)
|
|
261
|
+
} ms`;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Tiny format (minimal output).
|
|
266
|
+
* :method :url :status :res[content-length] - :response-time ms
|
|
267
|
+
*/
|
|
268
|
+
function formatTiny(
|
|
269
|
+
req: ExpressRequest,
|
|
270
|
+
res: ExpressResponse,
|
|
271
|
+
responseTime: number,
|
|
272
|
+
): string {
|
|
273
|
+
const contentLength = getContentLength(res) ?? "-";
|
|
274
|
+
return `${req.method} ${
|
|
275
|
+
req.originalUrl || req.url
|
|
276
|
+
} ${res.statusCode} ${contentLength} - ${responseTime.toFixed(3)} ms`;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Map of predefined format functions.
|
|
281
|
+
*/
|
|
282
|
+
const predefinedFormats: Record<PredefinedFormat, FormatFunction> = {
|
|
283
|
+
combined: formatCombined,
|
|
284
|
+
common: formatCommon,
|
|
285
|
+
dev: formatDev,
|
|
286
|
+
short: formatShort,
|
|
287
|
+
tiny: formatTiny,
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Normalize category to array format.
|
|
292
|
+
*/
|
|
293
|
+
function normalizeCategory(
|
|
294
|
+
category: string | readonly string[],
|
|
295
|
+
): readonly string[] {
|
|
296
|
+
return typeof category === "string" ? [category] : category;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Creates Express middleware for HTTP request logging using LogTape.
|
|
301
|
+
*
|
|
302
|
+
* This middleware provides Morgan-compatible request logging with LogTape
|
|
303
|
+
* as the backend, supporting structured logging and customizable formats.
|
|
304
|
+
*
|
|
305
|
+
* @example Basic usage
|
|
306
|
+
* ```typescript
|
|
307
|
+
* import express from "express";
|
|
308
|
+
* import { configure, getConsoleSink } from "@logtape/logtape";
|
|
309
|
+
* import { expressLogger } from "@logtape/express";
|
|
310
|
+
*
|
|
311
|
+
* await configure({
|
|
312
|
+
* sinks: { console: getConsoleSink() },
|
|
313
|
+
* loggers: [
|
|
314
|
+
* { category: ["express"], sinks: ["console"], lowestLevel: "info" }
|
|
315
|
+
* ],
|
|
316
|
+
* });
|
|
317
|
+
*
|
|
318
|
+
* const app = express();
|
|
319
|
+
* app.use(expressLogger());
|
|
320
|
+
*
|
|
321
|
+
* app.get("/", (req, res) => {
|
|
322
|
+
* res.json({ hello: "world" });
|
|
323
|
+
* });
|
|
324
|
+
*
|
|
325
|
+
* app.listen(3000);
|
|
326
|
+
* ```
|
|
327
|
+
*
|
|
328
|
+
* @example With custom options
|
|
329
|
+
* ```typescript
|
|
330
|
+
* app.use(expressLogger({
|
|
331
|
+
* category: ["myapp", "http"],
|
|
332
|
+
* level: "debug",
|
|
333
|
+
* format: "dev",
|
|
334
|
+
* skip: (req, res) => res.statusCode < 400,
|
|
335
|
+
* }));
|
|
336
|
+
* ```
|
|
337
|
+
*
|
|
338
|
+
* @example With custom format function
|
|
339
|
+
* ```typescript
|
|
340
|
+
* app.use(expressLogger({
|
|
341
|
+
* format: (req, res, responseTime) => ({
|
|
342
|
+
* method: req.method,
|
|
343
|
+
* path: req.path,
|
|
344
|
+
* status: res.statusCode,
|
|
345
|
+
* duration: responseTime,
|
|
346
|
+
* }),
|
|
347
|
+
* }));
|
|
348
|
+
* ```
|
|
349
|
+
*
|
|
350
|
+
* @param options Configuration options for the middleware.
|
|
351
|
+
* @returns Express middleware function.
|
|
352
|
+
* @since 1.3.0
|
|
353
|
+
*/
|
|
354
|
+
export function expressLogger(
|
|
355
|
+
options: ExpressLogTapeOptions = {},
|
|
356
|
+
): ExpressMiddleware {
|
|
357
|
+
const category = normalizeCategory(options.category ?? ["express"]);
|
|
358
|
+
const logger = getLogger(category);
|
|
359
|
+
const level = options.level ?? "info";
|
|
360
|
+
const formatOption = options.format ?? "combined";
|
|
361
|
+
const skip = options.skip ?? (() => false);
|
|
362
|
+
const immediate = options.immediate ?? false;
|
|
363
|
+
|
|
364
|
+
// Resolve format function
|
|
365
|
+
const formatFn: FormatFunction = typeof formatOption === "string"
|
|
366
|
+
? predefinedFormats[formatOption]
|
|
367
|
+
: formatOption;
|
|
368
|
+
|
|
369
|
+
const logMethod = logger[level].bind(logger);
|
|
370
|
+
|
|
371
|
+
return (
|
|
372
|
+
req: ExpressRequest,
|
|
373
|
+
res: ExpressResponse,
|
|
374
|
+
next: ExpressNextFunction,
|
|
375
|
+
): void => {
|
|
376
|
+
const startTime = Date.now();
|
|
377
|
+
|
|
378
|
+
// For immediate logging, log when request arrives
|
|
379
|
+
if (immediate) {
|
|
380
|
+
if (!skip(req, res)) {
|
|
381
|
+
const result = formatFn(req, res, 0);
|
|
382
|
+
if (typeof result === "string") {
|
|
383
|
+
logMethod(result);
|
|
384
|
+
} else {
|
|
385
|
+
logMethod("{method} {url}", result);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
next();
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// Log after response is sent
|
|
393
|
+
const logRequest = (): void => {
|
|
394
|
+
if (skip(req, res)) return;
|
|
395
|
+
|
|
396
|
+
const responseTime = Date.now() - startTime;
|
|
397
|
+
const result = formatFn(req, res, responseTime);
|
|
398
|
+
|
|
399
|
+
if (typeof result === "string") {
|
|
400
|
+
logMethod(result);
|
|
401
|
+
} else {
|
|
402
|
+
logMethod("{method} {url} {status} - {responseTime} ms", result);
|
|
403
|
+
}
|
|
404
|
+
};
|
|
405
|
+
|
|
406
|
+
// Listen for response finish event
|
|
407
|
+
res.on("finish", logRequest);
|
|
408
|
+
|
|
409
|
+
next();
|
|
410
|
+
};
|
|
411
|
+
}
|