@remix-run/logger-middleware 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Shopify Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, 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,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
package/README.md ADDED
@@ -0,0 +1,98 @@
1
+ # logger-middleware
2
+
3
+ Middleware for logging HTTP requests and responses for use with [`@remix-run/fetch-router`](https://github.com/remix-run/remix/tree/main/packages/fetch-router).
4
+
5
+ Logs information about HTTP requests and responses with customizable formatting.
6
+
7
+ ## Installation
8
+
9
+ ```sh
10
+ npm install @remix-run/logger-middleware
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import { createRouter } from '@remix-run/fetch-router'
17
+ import { logger } from '@remix-run/logger-middleware'
18
+
19
+ let router = createRouter({
20
+ middleware: [logger()],
21
+ })
22
+
23
+ // Logs: [19/Nov/2025:14:32:10 -0800] GET /users/123 200 1234
24
+ ```
25
+
26
+ ### Custom Format
27
+
28
+ You can use the `format` option to customize the log format. The following tokens are available:
29
+
30
+ - `%date` - Date and time in Apache/nginx format (dd/Mon/yyyy:HH:mm:ss ±zzzz)
31
+ - `%dateISO` - Date and time in ISO format
32
+ - `%duration` - Request duration in milliseconds
33
+ - `%contentLength` - Response Content-Length header
34
+ - `%contentType` - Response Content-Type header
35
+ - `%host` - Request URL host
36
+ - `%hostname` - Request URL hostname
37
+ - `%method` - Request method
38
+ - `%path` - Request pathname + search
39
+ - `%pathname` - Request pathname
40
+ - `%port` - Request port
41
+ - `%query` - Request query string (search)
42
+ - `%referer` - Request Referer header
43
+ - `%search` - Request search string
44
+ - `%status` - Response status code
45
+ - `%statusText` - Response status text
46
+ - `%url` - Full request URL
47
+ - `%userAgent` - Request User-Agent header
48
+
49
+ ```ts
50
+ let router = createRouter({
51
+ middleware: [
52
+ logger({
53
+ format: '%method %path - %status (%duration ms)',
54
+ }),
55
+ ],
56
+ })
57
+ // Logs: GET /users/123 - 200 (42 ms)
58
+ ```
59
+
60
+ For Apache-style combined log format, you can use the following format:
61
+
62
+ ```ts
63
+ let router = createRouter({
64
+ middleware: [
65
+ logger({
66
+ format: '%host - - [%date] "%method %path" %status %contentLength "%referer" "%userAgent"',
67
+ }),
68
+ ],
69
+ })
70
+ ```
71
+
72
+ ### Custom Logger
73
+
74
+ You can use a custom logger to write logs to a file or other stream.
75
+
76
+ ```ts
77
+ import { createWriteStream } from 'node:fs'
78
+
79
+ let logStream = createWriteStream('access.log', { flags: 'a' })
80
+
81
+ let router = createRouter({
82
+ middleware: [
83
+ logger({
84
+ log(message) {
85
+ logStream.write(message + '\n')
86
+ },
87
+ }),
88
+ ],
89
+ })
90
+ ```
91
+
92
+ ## Related Packages
93
+
94
+ - [`fetch-router`](https://github.com/remix-run/remix/tree/main/packages/fetch-router) - Router for the web Fetch API
95
+
96
+ ## License
97
+
98
+ See [LICENSE](https://github.com/remix-run/remix/blob/main/LICENSE)
@@ -0,0 +1,2 @@
1
+ export { type LoggerOptions, logger } from './lib/logger.ts';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,aAAa,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { logger } from "./lib/logger.js";
@@ -0,0 +1,37 @@
1
+ import type { Middleware } from '@remix-run/fetch-router';
2
+ export interface LoggerOptions {
3
+ /**
4
+ * The format to use for log messages. Defaults to `[%date] %method %path %status %contentLength`.
5
+ *
6
+ * The following tokens are available:
7
+ *
8
+ * - `%date` - The date and time of the request in Apache/nginx log format (dd/Mon/yyyy:HH:mm:ss ±zzzz).
9
+ * - `%dateISO` - The date and time of the request in ISO format.
10
+ * - `%duration` - The duration of the request in milliseconds.
11
+ * - `%contentLength` - The `Content-Length` header of the response.
12
+ * - `%contentType` - The `Content-Type` header of the response.
13
+ * - `%host` - The host of the request URL.
14
+ * - `%hostname` - The hostname of the request URL.
15
+ * - `%method` - The method of the request.
16
+ * - `%path` - The pathname + search of the request URL.
17
+ * - `%pathname` - The pathname of the request URL.
18
+ * - `%port` - The port of the request.
19
+ * - `%query` - The query (search) string of the request URL.
20
+ * - `%referer` - The `Referer` header of the request.
21
+ * - `%search` - The search string of the request URL.
22
+ * - `%status` - The status code of the response.
23
+ * - `%statusText` - The status text of the response.
24
+ * - `%url` - The full URL of the request.
25
+ * - `%userAgent` - The `User-Agent` header of the request.
26
+ */
27
+ format?: string;
28
+ /**
29
+ * The function to use to log messages. Defaults to `console.log`.
30
+ */
31
+ log?: (message: string) => void;
32
+ }
33
+ /**
34
+ * Creates a middleware handler that logs various request/response info.
35
+ */
36
+ export declare function logger(options?: LoggerOptions): Middleware;
37
+ //# sourceMappingURL=logger.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../src/lib/logger.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAA;AAEzD,MAAM,WAAW,aAAa;IAC5B;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;IACf;;OAEG;IACH,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAA;CAChC;AAED;;GAEG;AACH,wBAAgB,MAAM,CAAC,OAAO,GAAE,aAAkB,GAAG,UAAU,CAoC9D"}
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Creates a middleware handler that logs various request/response info.
3
+ */
4
+ export function logger(options = {}) {
5
+ let { format = '[%date] %method %path %status %contentLength', log = console.log } = options;
6
+ return async ({ request, url }, next) => {
7
+ let start = new Date();
8
+ let response = await next();
9
+ let end = new Date();
10
+ let tokens = {
11
+ date: () => formatApacheDate(start),
12
+ dateISO: () => start.toISOString(),
13
+ duration: () => String(end.getTime() - start.getTime()),
14
+ contentLength: () => response.headers.get('Content-Length') ?? '-',
15
+ contentType: () => response.headers.get('Content-Type') ?? '-',
16
+ host: () => url.host,
17
+ hostname: () => url.hostname,
18
+ method: () => request.method,
19
+ path: () => url.pathname + url.search,
20
+ pathname: () => url.pathname,
21
+ port: () => url.port,
22
+ protocol: () => url.protocol,
23
+ query: () => url.search,
24
+ referer: () => request.headers.get('Referer') ?? '-',
25
+ search: () => url.search,
26
+ status: () => String(response.status),
27
+ statusText: () => response.statusText,
28
+ url: () => url.href,
29
+ userAgent: () => request.headers.get('User-Agent') ?? '-',
30
+ };
31
+ let message = format.replace(/%(\w+)/g, (_, key) => tokens[key]?.() ?? '-');
32
+ log(message);
33
+ return response;
34
+ };
35
+ }
36
+ const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
37
+ /**
38
+ * Formats a date in Apache/nginx log format: "dd/Mon/yyyy:HH:mm:ss ±zzzz"
39
+ * Example: "23/Sep/2025:11:34:12 -0700"
40
+ */
41
+ function formatApacheDate(date) {
42
+ let day = String(date.getDate()).padStart(2, '0');
43
+ let month = months[date.getMonth()];
44
+ let year = date.getFullYear();
45
+ let hours = String(date.getHours()).padStart(2, '0');
46
+ let minutes = String(date.getMinutes()).padStart(2, '0');
47
+ let seconds = String(date.getSeconds()).padStart(2, '0');
48
+ // Get timezone offset in minutes and convert to ±HHMM format
49
+ let timezoneOffset = date.getTimezoneOffset();
50
+ let sign = timezoneOffset <= 0 ? '+' : '-';
51
+ let offsetHours = String(Math.floor(Math.abs(timezoneOffset) / 60)).padStart(2, '0');
52
+ let offsetMinutes = String(Math.abs(timezoneOffset) % 60).padStart(2, '0');
53
+ let timezone = `${sign}${offsetHours}${offsetMinutes}`;
54
+ return `${day}/${month}/${year}:${hours}:${minutes}:${seconds} ${timezone}`;
55
+ }
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@remix-run/logger-middleware",
3
+ "version": "0.0.0",
4
+ "description": "Middleware for logging HTTP requests and responses",
5
+ "author": "Michael Jackson <mjijackson@gmail.com>",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/remix-run/remix.git",
10
+ "directory": "packages/logger-middleware"
11
+ },
12
+ "homepage": "https://github.com/remix-run/remix/tree/main/packages/logger-middleware#readme",
13
+ "files": [
14
+ "LICENSE",
15
+ "README.md",
16
+ "dist",
17
+ "src",
18
+ "!src/**/*.test.ts"
19
+ ],
20
+ "type": "module",
21
+ "exports": {
22
+ ".": {
23
+ "types": "./dist/index.d.ts",
24
+ "default": "./dist/index.js"
25
+ },
26
+ "./package.json": "./package.json"
27
+ },
28
+ "devDependencies": {
29
+ "@types/node": "^24.6.0",
30
+ "typescript": "^5.9.3",
31
+ "@remix-run/fetch-router": "0.9.0"
32
+ },
33
+ "peerDependencies": {
34
+ "@remix-run/fetch-router": "^0.9.0"
35
+ },
36
+ "keywords": [
37
+ "fetch",
38
+ "router",
39
+ "middleware",
40
+ "logger",
41
+ "logging",
42
+ "http-logger"
43
+ ],
44
+ "scripts": {
45
+ "build": "tsc -p tsconfig.build.json",
46
+ "clean": "git clean -fdX",
47
+ "test": "node --disable-warning=ExperimentalWarning --test './src/**/*.test.ts'",
48
+ "typecheck": "tsc --noEmit"
49
+ }
50
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { type LoggerOptions, logger } from './lib/logger.ts'
2
+
@@ -0,0 +1,98 @@
1
+ import type { Middleware } from '@remix-run/fetch-router'
2
+
3
+ export interface LoggerOptions {
4
+ /**
5
+ * The format to use for log messages. Defaults to `[%date] %method %path %status %contentLength`.
6
+ *
7
+ * The following tokens are available:
8
+ *
9
+ * - `%date` - The date and time of the request in Apache/nginx log format (dd/Mon/yyyy:HH:mm:ss ±zzzz).
10
+ * - `%dateISO` - The date and time of the request in ISO format.
11
+ * - `%duration` - The duration of the request in milliseconds.
12
+ * - `%contentLength` - The `Content-Length` header of the response.
13
+ * - `%contentType` - The `Content-Type` header of the response.
14
+ * - `%host` - The host of the request URL.
15
+ * - `%hostname` - The hostname of the request URL.
16
+ * - `%method` - The method of the request.
17
+ * - `%path` - The pathname + search of the request URL.
18
+ * - `%pathname` - The pathname of the request URL.
19
+ * - `%port` - The port of the request.
20
+ * - `%query` - The query (search) string of the request URL.
21
+ * - `%referer` - The `Referer` header of the request.
22
+ * - `%search` - The search string of the request URL.
23
+ * - `%status` - The status code of the response.
24
+ * - `%statusText` - The status text of the response.
25
+ * - `%url` - The full URL of the request.
26
+ * - `%userAgent` - The `User-Agent` header of the request.
27
+ */
28
+ format?: string
29
+ /**
30
+ * The function to use to log messages. Defaults to `console.log`.
31
+ */
32
+ log?: (message: string) => void
33
+ }
34
+
35
+ /**
36
+ * Creates a middleware handler that logs various request/response info.
37
+ */
38
+ export function logger(options: LoggerOptions = {}): Middleware {
39
+ let { format = '[%date] %method %path %status %contentLength', log = console.log } = options
40
+
41
+ return async ({ request, url }, next) => {
42
+ let start = new Date()
43
+ let response = await next()
44
+ let end = new Date()
45
+
46
+ let tokens: Record<string, () => string> = {
47
+ date: () => formatApacheDate(start),
48
+ dateISO: () => start.toISOString(),
49
+ duration: () => String(end.getTime() - start.getTime()),
50
+ contentLength: () => response.headers.get('Content-Length') ?? '-',
51
+ contentType: () => response.headers.get('Content-Type') ?? '-',
52
+ host: () => url.host,
53
+ hostname: () => url.hostname,
54
+ method: () => request.method,
55
+ path: () => url.pathname + url.search,
56
+ pathname: () => url.pathname,
57
+ port: () => url.port,
58
+ protocol: () => url.protocol,
59
+ query: () => url.search,
60
+ referer: () => request.headers.get('Referer') ?? '-',
61
+ search: () => url.search,
62
+ status: () => String(response.status),
63
+ statusText: () => response.statusText,
64
+ url: () => url.href,
65
+ userAgent: () => request.headers.get('User-Agent') ?? '-',
66
+ }
67
+
68
+ let message = format.replace(/%(\w+)/g, (_, key) => tokens[key]?.() ?? '-')
69
+
70
+ log(message)
71
+
72
+ return response
73
+ }
74
+ }
75
+
76
+ const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
77
+
78
+ /**
79
+ * Formats a date in Apache/nginx log format: "dd/Mon/yyyy:HH:mm:ss ±zzzz"
80
+ * Example: "23/Sep/2025:11:34:12 -0700"
81
+ */
82
+ function formatApacheDate(date: Date): string {
83
+ let day = String(date.getDate()).padStart(2, '0')
84
+ let month = months[date.getMonth()]
85
+ let year = date.getFullYear()
86
+ let hours = String(date.getHours()).padStart(2, '0')
87
+ let minutes = String(date.getMinutes()).padStart(2, '0')
88
+ let seconds = String(date.getSeconds()).padStart(2, '0')
89
+
90
+ // Get timezone offset in minutes and convert to ±HHMM format
91
+ let timezoneOffset = date.getTimezoneOffset()
92
+ let sign = timezoneOffset <= 0 ? '+' : '-'
93
+ let offsetHours = String(Math.floor(Math.abs(timezoneOffset) / 60)).padStart(2, '0')
94
+ let offsetMinutes = String(Math.abs(timezoneOffset) % 60).padStart(2, '0')
95
+ let timezone = `${sign}${offsetHours}${offsetMinutes}`
96
+
97
+ return `${day}/${month}/${year}:${hours}:${minutes}:${seconds} ${timezone}`
98
+ }