@logtape/hono 2.2.0-dev.766 → 2.2.0-dev.767
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/README.md +16 -7
- package/dist/mod.cjs +76 -4
- package/dist/mod.d.cts +20 -6
- package/dist/mod.d.cts.map +1 -1
- package/dist/mod.d.ts +20 -6
- package/dist/mod.d.ts.map +1 -1
- package/dist/mod.js +76 -4
- package/dist/mod.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -116,15 +116,24 @@ app.use(honoLogger({
|
|
|
116
116
|
Predefined formats
|
|
117
117
|
------------------
|
|
118
118
|
|
|
119
|
-
The middleware supports
|
|
120
|
-
|
|
121
|
-
- `"combined"`:
|
|
122
|
-
- `"common"`:
|
|
119
|
+
The middleware supports structured presets and text presets:
|
|
120
|
+
|
|
121
|
+
- `"structured-combined"`: Structured request properties (default)
|
|
122
|
+
- `"structured-common"`: Structured request properties without
|
|
123
|
+
`referrer`/`userAgent`
|
|
124
|
+
- `"combined"`: Deprecated alias for `"structured-combined"`
|
|
125
|
+
- `"common"`: Deprecated alias for `"structured-common"`
|
|
126
|
+
- `"morgan-combined"`: Morgan-compatible Apache combined access log output
|
|
127
|
+
- `"morgan-common"`: Morgan-compatible Apache common access log output
|
|
123
128
|
- `"dev"`: Concise output for development (e.g.,
|
|
124
129
|
`GET /path 200 1.234 ms - 123`)
|
|
125
|
-
- `"short"`: Shorter format with
|
|
130
|
+
- `"short"`: Shorter format with URL
|
|
126
131
|
- `"tiny"`: Minimal output
|
|
127
132
|
|
|
133
|
+
Hono does not expose socket-level fields consistently across runtimes. The
|
|
134
|
+
Morgan-compatible text formats use `X-Forwarded-For` for the remote address and
|
|
135
|
+
render unavailable fields, such as the HTTP version, as `-`.
|
|
136
|
+
|
|
128
137
|
|
|
129
138
|
Custom format function
|
|
130
139
|
----------------------
|
|
@@ -160,8 +169,8 @@ app.use(honoLogger({
|
|
|
160
169
|
Structured logging output
|
|
161
170
|
-------------------------
|
|
162
171
|
|
|
163
|
-
When using the `"combined"` format (default), the middleware logs
|
|
164
|
-
data that includes:
|
|
172
|
+
When using the `"structured-combined"` format (default), the middleware logs
|
|
173
|
+
structured data that includes:
|
|
165
174
|
|
|
166
175
|
- `method`: HTTP request method
|
|
167
176
|
- `url`: Request URL
|
package/dist/mod.cjs
CHANGED
|
@@ -173,16 +173,67 @@ function withRequestLogContext(result, context) {
|
|
|
173
173
|
...context
|
|
174
174
|
};
|
|
175
175
|
}
|
|
176
|
+
const clfMonths = [
|
|
177
|
+
"Jan",
|
|
178
|
+
"Feb",
|
|
179
|
+
"Mar",
|
|
180
|
+
"Apr",
|
|
181
|
+
"May",
|
|
182
|
+
"Jun",
|
|
183
|
+
"Jul",
|
|
184
|
+
"Aug",
|
|
185
|
+
"Sep",
|
|
186
|
+
"Oct",
|
|
187
|
+
"Nov",
|
|
188
|
+
"Dec"
|
|
189
|
+
];
|
|
190
|
+
function pad2(value) {
|
|
191
|
+
return value.toString().padStart(2, "0");
|
|
192
|
+
}
|
|
193
|
+
function formatClfDate(timestamp = Date.now()) {
|
|
194
|
+
const date = new Date(timestamp);
|
|
195
|
+
return `${pad2(date.getUTCDate())}/${clfMonths[date.getUTCMonth()]}/${date.getUTCFullYear()}:${pad2(date.getUTCHours())}:${pad2(date.getUTCMinutes())}:${pad2(date.getUTCSeconds())} +0000`;
|
|
196
|
+
}
|
|
197
|
+
function escapeAccessLogValue(value, escapeSpaces) {
|
|
198
|
+
const escaped = String(value).replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\r/g, "\\r").replace(/\n/g, "\\n").replace(/\t/g, "\\t");
|
|
199
|
+
return escapeSpaces ? escaped.replace(/ /g, "\\x20") : escaped;
|
|
200
|
+
}
|
|
201
|
+
function formatAccessLogToken(value) {
|
|
202
|
+
if (value == null || value === "") return "-";
|
|
203
|
+
return escapeAccessLogValue(value, true);
|
|
204
|
+
}
|
|
205
|
+
function formatAccessLogQuotedToken(value) {
|
|
206
|
+
if (value == null || value === "") return "\"-\"";
|
|
207
|
+
return `"${escapeAccessLogValue(value, false)}"`;
|
|
208
|
+
}
|
|
209
|
+
function getRemoteUser(c) {
|
|
210
|
+
const authorization = c.req.header("authorization");
|
|
211
|
+
if (authorization == null) return void 0;
|
|
212
|
+
const match = /^Basic\s+(.+)$/i.exec(authorization);
|
|
213
|
+
if (match == null || typeof globalThis.atob !== "function") return void 0;
|
|
214
|
+
try {
|
|
215
|
+
const decoded = globalThis.atob(match[1]);
|
|
216
|
+
const colonIndex = decoded.indexOf(":");
|
|
217
|
+
const user = colonIndex < 0 ? decoded : decoded.slice(0, colonIndex);
|
|
218
|
+
return user === "" ? void 0 : user;
|
|
219
|
+
} catch {
|
|
220
|
+
return void 0;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
function getRequestTarget(c) {
|
|
224
|
+
const url = new URL(c.req.url, "http://localhost");
|
|
225
|
+
return `${url.pathname}${url.search}`;
|
|
226
|
+
}
|
|
176
227
|
/**
|
|
177
|
-
*
|
|
228
|
+
* Structured combined format.
|
|
178
229
|
* Returns all structured properties.
|
|
179
230
|
*/
|
|
180
231
|
function formatCombined(c, responseTime) {
|
|
181
232
|
return { ...buildProperties(c, responseTime) };
|
|
182
233
|
}
|
|
183
234
|
/**
|
|
184
|
-
*
|
|
185
|
-
* Like combined but without referrer and userAgent.
|
|
235
|
+
* Structured common format.
|
|
236
|
+
* Like structured combined but without referrer and userAgent.
|
|
186
237
|
*/
|
|
187
238
|
function formatCommon(c, responseTime) {
|
|
188
239
|
const props = buildProperties(c, responseTime);
|
|
@@ -190,6 +241,23 @@ function formatCommon(c, responseTime) {
|
|
|
190
241
|
return rest;
|
|
191
242
|
}
|
|
192
243
|
/**
|
|
244
|
+
* Morgan combined format.
|
|
245
|
+
* :remote-addr - :remote-user [:date[clf]]
|
|
246
|
+
* ":method :url HTTP/:http-version" :status :res[content-length]
|
|
247
|
+
* ":referrer" ":user-agent"
|
|
248
|
+
*/
|
|
249
|
+
function formatMorganCombined(c) {
|
|
250
|
+
return `${formatAccessLogToken(getRemoteAddr(c))} - ${formatAccessLogToken(getRemoteUser(c))} [${formatClfDate()}] "${formatAccessLogToken(c.req.method)} ${formatAccessLogToken(getRequestTarget(c))} HTTP/-" ${formatAccessLogToken(c.res.status)} ${formatAccessLogToken(getContentLength(c))} ${formatAccessLogQuotedToken(getReferrer(c))} ${formatAccessLogQuotedToken(getUserAgent(c))}`;
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Morgan common format.
|
|
254
|
+
* :remote-addr - :remote-user [:date[clf]]
|
|
255
|
+
* ":method :url HTTP/:http-version" :status :res[content-length]
|
|
256
|
+
*/
|
|
257
|
+
function formatMorganCommon(c) {
|
|
258
|
+
return `${formatAccessLogToken(getRemoteAddr(c))} - ${formatAccessLogToken(getRemoteUser(c))} [${formatClfDate()}] "${formatAccessLogToken(c.req.method)} ${formatAccessLogToken(getRequestTarget(c))} HTTP/-" ${formatAccessLogToken(c.res.status)} ${formatAccessLogToken(getContentLength(c))}`;
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
193
261
|
* Dev format (colored output for development).
|
|
194
262
|
* :method :path :status :response-time ms - :res[content-length]
|
|
195
263
|
*/
|
|
@@ -219,6 +287,10 @@ function formatTiny(c, responseTime) {
|
|
|
219
287
|
const predefinedFormats = {
|
|
220
288
|
combined: formatCombined,
|
|
221
289
|
common: formatCommon,
|
|
290
|
+
"structured-combined": formatCombined,
|
|
291
|
+
"structured-common": formatCommon,
|
|
292
|
+
"morgan-combined": formatMorganCombined,
|
|
293
|
+
"morgan-common": formatMorganCommon,
|
|
222
294
|
dev: formatDev,
|
|
223
295
|
short: formatShort,
|
|
224
296
|
tiny: formatTiny
|
|
@@ -286,7 +358,7 @@ function honoLogger(options = {}) {
|
|
|
286
358
|
const category = normalizeCategory(options.category ?? ["hono"]);
|
|
287
359
|
const logger = (0, __logtape_logtape.getLogger)(category);
|
|
288
360
|
const level = options.level ?? "info";
|
|
289
|
-
const formatOption = options.format ?? "combined";
|
|
361
|
+
const formatOption = options.format ?? "structured-combined";
|
|
290
362
|
const skip = options.skip ?? (() => false);
|
|
291
363
|
const logRequest = options.logRequest ?? false;
|
|
292
364
|
const contextOptions = normalizeRequestContextOptions(options.context);
|
package/dist/mod.d.cts
CHANGED
|
@@ -13,10 +13,17 @@ import { Context, MiddlewareHandler } from "hono";
|
|
|
13
13
|
*/
|
|
14
14
|
interface HonoContext extends Context<any, any, any> {}
|
|
15
15
|
/**
|
|
16
|
-
* Predefined log format names
|
|
16
|
+
* Predefined log format names.
|
|
17
17
|
* @since 1.3.0
|
|
18
18
|
*/
|
|
19
|
-
type PredefinedFormat =
|
|
19
|
+
type PredefinedFormat =
|
|
20
|
+
/**
|
|
21
|
+
* @deprecated Use `"structured-combined"` instead.
|
|
22
|
+
*/
|
|
23
|
+
"combined"
|
|
24
|
+
/**
|
|
25
|
+
* @deprecated Use `"structured-common"` instead.
|
|
26
|
+
*/ | "common" | "structured-combined" | "structured-common" | "morgan-combined" | "morgan-common" | "dev" | "short" | "tiny";
|
|
20
27
|
/**
|
|
21
28
|
* Custom format function for request logging.
|
|
22
29
|
*
|
|
@@ -124,14 +131,21 @@ interface HonoLogTapeOptions {
|
|
|
124
131
|
* The format for log output.
|
|
125
132
|
* Can be a predefined format name or a custom format function.
|
|
126
133
|
*
|
|
127
|
-
*
|
|
128
|
-
* - `"combined"` -
|
|
129
|
-
* - `"common"` -
|
|
134
|
+
* Structured formats:
|
|
135
|
+
* - `"structured-combined"` - Structured request properties (default)
|
|
136
|
+
* - `"structured-common"` - Structured request properties without
|
|
137
|
+
* referrer/userAgent
|
|
138
|
+
* - `"combined"` - Deprecated alias for `"structured-combined"`
|
|
139
|
+
* - `"common"` - Deprecated alias for `"structured-common"`
|
|
140
|
+
*
|
|
141
|
+
* Text formats:
|
|
142
|
+
* - `"morgan-combined"` - Morgan-compatible combined access log (string)
|
|
143
|
+
* - `"morgan-common"` - Morgan-compatible common access log (string)
|
|
130
144
|
* - `"dev"` - Concise colored output for development (string)
|
|
131
145
|
* - `"short"` - Shorter than common (string)
|
|
132
146
|
* - `"tiny"` - Minimal output (string)
|
|
133
147
|
*
|
|
134
|
-
* @default "combined"
|
|
148
|
+
* @default "structured-combined"
|
|
135
149
|
*/
|
|
136
150
|
readonly format?: PredefinedFormat | FormatFunction;
|
|
137
151
|
/**
|
package/dist/mod.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mod.d.cts","names":[],"sources":["../src/mod.ts"],"sourcesContent":[],"mappings":";;;;;;AAeA;AAMA;
|
|
1
|
+
{"version":3,"file":"mod.d.cts","names":[],"sources":["../src/mod.ts"],"sourcesContent":[],"mappings":";;;;;;AAeA;AAMA;AAyBA;;;;AAGoB;AAMH,UAxCA,WAAA,SAAoB,OAwCA,CAAA,GAAA,EAAA,GAAA,EAAA,GAAA,CAAA,CAAA,CAuBrC;AAaA;AAqCA;;;AAW8B,KAtHlB,gBAAA;;;;;AA6H4B;AAOxC;GAPwC,GAOL,QAWhB,GAAA,qBAAA,GAAA,mBAAA,GAAA,iBAAA,GAAA,eAAA,GAAA,KAAA,GAAA,OAAA,GAAA,MAAA;;;;;AA6DiC;AAiepD;;;AAEG,KAtpBS,cAAA,GAspBT,CAAA,CAAA,EArpBE,WAqpBF,EAAA,YAAA,EAAA,MAAA,EAAA,GAAA,MAAA,GAnpBW,MAmpBX,CAAA,MAAA,EAAA,OAAA,CAAA;AAAiB;;;;UA7oBH,oBAAA;;;;;;;;;;;;;;;;;;;;;;KAuBL,mBAAA;;;;;UAaK,gBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAqCA,qBAAA;;;;;iCAKgB;;;;;8BAMH;;;;wBAMvB,gBACA,0BAA0B,QAAQ;;;;;;UAOxB,kBAAA;;;;;;;;;;mBAWE;;;;;;;;;;;;;;;;;;;;;oBAsBC,mBAAmB;;;;;;;;;;;;;;sBAejB;;;;;;;;;;;;;;;;;;;;;;+BAwBS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAief,UAAA,WACL,qBACR"}
|
package/dist/mod.d.ts
CHANGED
|
@@ -13,10 +13,17 @@ import { Context, MiddlewareHandler } from "hono";
|
|
|
13
13
|
*/
|
|
14
14
|
interface HonoContext extends Context<any, any, any> {}
|
|
15
15
|
/**
|
|
16
|
-
* Predefined log format names
|
|
16
|
+
* Predefined log format names.
|
|
17
17
|
* @since 1.3.0
|
|
18
18
|
*/
|
|
19
|
-
type PredefinedFormat =
|
|
19
|
+
type PredefinedFormat =
|
|
20
|
+
/**
|
|
21
|
+
* @deprecated Use `"structured-combined"` instead.
|
|
22
|
+
*/
|
|
23
|
+
"combined"
|
|
24
|
+
/**
|
|
25
|
+
* @deprecated Use `"structured-common"` instead.
|
|
26
|
+
*/ | "common" | "structured-combined" | "structured-common" | "morgan-combined" | "morgan-common" | "dev" | "short" | "tiny";
|
|
20
27
|
/**
|
|
21
28
|
* Custom format function for request logging.
|
|
22
29
|
*
|
|
@@ -124,14 +131,21 @@ interface HonoLogTapeOptions {
|
|
|
124
131
|
* The format for log output.
|
|
125
132
|
* Can be a predefined format name or a custom format function.
|
|
126
133
|
*
|
|
127
|
-
*
|
|
128
|
-
* - `"combined"` -
|
|
129
|
-
* - `"common"` -
|
|
134
|
+
* Structured formats:
|
|
135
|
+
* - `"structured-combined"` - Structured request properties (default)
|
|
136
|
+
* - `"structured-common"` - Structured request properties without
|
|
137
|
+
* referrer/userAgent
|
|
138
|
+
* - `"combined"` - Deprecated alias for `"structured-combined"`
|
|
139
|
+
* - `"common"` - Deprecated alias for `"structured-common"`
|
|
140
|
+
*
|
|
141
|
+
* Text formats:
|
|
142
|
+
* - `"morgan-combined"` - Morgan-compatible combined access log (string)
|
|
143
|
+
* - `"morgan-common"` - Morgan-compatible common access log (string)
|
|
130
144
|
* - `"dev"` - Concise colored output for development (string)
|
|
131
145
|
* - `"short"` - Shorter than common (string)
|
|
132
146
|
* - `"tiny"` - Minimal output (string)
|
|
133
147
|
*
|
|
134
|
-
* @default "combined"
|
|
148
|
+
* @default "structured-combined"
|
|
135
149
|
*/
|
|
136
150
|
readonly format?: PredefinedFormat | FormatFunction;
|
|
137
151
|
/**
|
package/dist/mod.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mod.d.ts","names":[],"sources":["../src/mod.ts"],"sourcesContent":[],"mappings":";;;;;;AAeA;AAMA;
|
|
1
|
+
{"version":3,"file":"mod.d.ts","names":[],"sources":["../src/mod.ts"],"sourcesContent":[],"mappings":";;;;;;AAeA;AAMA;AAyBA;;;;AAGoB;AAMH,UAxCA,WAAA,SAAoB,OAwCA,CAAA,GAAA,EAAA,GAAA,EAAA,GAAA,CAAA,CAAA,CAuBrC;AAaA;AAqCA;;;AAW8B,KAtHlB,gBAAA;;;;;AA6H4B;AAOxC;GAPwC,GAOL,QAWhB,GAAA,qBAAA,GAAA,mBAAA,GAAA,iBAAA,GAAA,eAAA,GAAA,KAAA,GAAA,OAAA,GAAA,MAAA;;;;;AA6DiC;AAiepD;;;AAEG,KAtpBS,cAAA,GAspBT,CAAA,CAAA,EArpBE,WAqpBF,EAAA,YAAA,EAAA,MAAA,EAAA,GAAA,MAAA,GAnpBW,MAmpBX,CAAA,MAAA,EAAA,OAAA,CAAA;AAAiB;;;;UA7oBH,oBAAA;;;;;;;;;;;;;;;;;;;;;;KAuBL,mBAAA;;;;;UAaK,gBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAqCA,qBAAA;;;;;iCAKgB;;;;;8BAMH;;;;wBAMvB,gBACA,0BAA0B,QAAQ;;;;;;UAOxB,kBAAA;;;;;;;;;;mBAWE;;;;;;;;;;;;;;;;;;;;;oBAsBC,mBAAmB;;;;;;;;;;;;;;sBAejB;;;;;;;;;;;;;;;;;;;;;;+BAwBS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAief,UAAA,WACL,qBACR"}
|
package/dist/mod.js
CHANGED
|
@@ -172,16 +172,67 @@ function withRequestLogContext(result, context) {
|
|
|
172
172
|
...context
|
|
173
173
|
};
|
|
174
174
|
}
|
|
175
|
+
const clfMonths = [
|
|
176
|
+
"Jan",
|
|
177
|
+
"Feb",
|
|
178
|
+
"Mar",
|
|
179
|
+
"Apr",
|
|
180
|
+
"May",
|
|
181
|
+
"Jun",
|
|
182
|
+
"Jul",
|
|
183
|
+
"Aug",
|
|
184
|
+
"Sep",
|
|
185
|
+
"Oct",
|
|
186
|
+
"Nov",
|
|
187
|
+
"Dec"
|
|
188
|
+
];
|
|
189
|
+
function pad2(value) {
|
|
190
|
+
return value.toString().padStart(2, "0");
|
|
191
|
+
}
|
|
192
|
+
function formatClfDate(timestamp = Date.now()) {
|
|
193
|
+
const date = new Date(timestamp);
|
|
194
|
+
return `${pad2(date.getUTCDate())}/${clfMonths[date.getUTCMonth()]}/${date.getUTCFullYear()}:${pad2(date.getUTCHours())}:${pad2(date.getUTCMinutes())}:${pad2(date.getUTCSeconds())} +0000`;
|
|
195
|
+
}
|
|
196
|
+
function escapeAccessLogValue(value, escapeSpaces) {
|
|
197
|
+
const escaped = String(value).replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\r/g, "\\r").replace(/\n/g, "\\n").replace(/\t/g, "\\t");
|
|
198
|
+
return escapeSpaces ? escaped.replace(/ /g, "\\x20") : escaped;
|
|
199
|
+
}
|
|
200
|
+
function formatAccessLogToken(value) {
|
|
201
|
+
if (value == null || value === "") return "-";
|
|
202
|
+
return escapeAccessLogValue(value, true);
|
|
203
|
+
}
|
|
204
|
+
function formatAccessLogQuotedToken(value) {
|
|
205
|
+
if (value == null || value === "") return "\"-\"";
|
|
206
|
+
return `"${escapeAccessLogValue(value, false)}"`;
|
|
207
|
+
}
|
|
208
|
+
function getRemoteUser(c) {
|
|
209
|
+
const authorization = c.req.header("authorization");
|
|
210
|
+
if (authorization == null) return void 0;
|
|
211
|
+
const match = /^Basic\s+(.+)$/i.exec(authorization);
|
|
212
|
+
if (match == null || typeof globalThis.atob !== "function") return void 0;
|
|
213
|
+
try {
|
|
214
|
+
const decoded = globalThis.atob(match[1]);
|
|
215
|
+
const colonIndex = decoded.indexOf(":");
|
|
216
|
+
const user = colonIndex < 0 ? decoded : decoded.slice(0, colonIndex);
|
|
217
|
+
return user === "" ? void 0 : user;
|
|
218
|
+
} catch {
|
|
219
|
+
return void 0;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
function getRequestTarget(c) {
|
|
223
|
+
const url = new URL(c.req.url, "http://localhost");
|
|
224
|
+
return `${url.pathname}${url.search}`;
|
|
225
|
+
}
|
|
175
226
|
/**
|
|
176
|
-
*
|
|
227
|
+
* Structured combined format.
|
|
177
228
|
* Returns all structured properties.
|
|
178
229
|
*/
|
|
179
230
|
function formatCombined(c, responseTime) {
|
|
180
231
|
return { ...buildProperties(c, responseTime) };
|
|
181
232
|
}
|
|
182
233
|
/**
|
|
183
|
-
*
|
|
184
|
-
* Like combined but without referrer and userAgent.
|
|
234
|
+
* Structured common format.
|
|
235
|
+
* Like structured combined but without referrer and userAgent.
|
|
185
236
|
*/
|
|
186
237
|
function formatCommon(c, responseTime) {
|
|
187
238
|
const props = buildProperties(c, responseTime);
|
|
@@ -189,6 +240,23 @@ function formatCommon(c, responseTime) {
|
|
|
189
240
|
return rest;
|
|
190
241
|
}
|
|
191
242
|
/**
|
|
243
|
+
* Morgan combined format.
|
|
244
|
+
* :remote-addr - :remote-user [:date[clf]]
|
|
245
|
+
* ":method :url HTTP/:http-version" :status :res[content-length]
|
|
246
|
+
* ":referrer" ":user-agent"
|
|
247
|
+
*/
|
|
248
|
+
function formatMorganCombined(c) {
|
|
249
|
+
return `${formatAccessLogToken(getRemoteAddr(c))} - ${formatAccessLogToken(getRemoteUser(c))} [${formatClfDate()}] "${formatAccessLogToken(c.req.method)} ${formatAccessLogToken(getRequestTarget(c))} HTTP/-" ${formatAccessLogToken(c.res.status)} ${formatAccessLogToken(getContentLength(c))} ${formatAccessLogQuotedToken(getReferrer(c))} ${formatAccessLogQuotedToken(getUserAgent(c))}`;
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Morgan common format.
|
|
253
|
+
* :remote-addr - :remote-user [:date[clf]]
|
|
254
|
+
* ":method :url HTTP/:http-version" :status :res[content-length]
|
|
255
|
+
*/
|
|
256
|
+
function formatMorganCommon(c) {
|
|
257
|
+
return `${formatAccessLogToken(getRemoteAddr(c))} - ${formatAccessLogToken(getRemoteUser(c))} [${formatClfDate()}] "${formatAccessLogToken(c.req.method)} ${formatAccessLogToken(getRequestTarget(c))} HTTP/-" ${formatAccessLogToken(c.res.status)} ${formatAccessLogToken(getContentLength(c))}`;
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
192
260
|
* Dev format (colored output for development).
|
|
193
261
|
* :method :path :status :response-time ms - :res[content-length]
|
|
194
262
|
*/
|
|
@@ -218,6 +286,10 @@ function formatTiny(c, responseTime) {
|
|
|
218
286
|
const predefinedFormats = {
|
|
219
287
|
combined: formatCombined,
|
|
220
288
|
common: formatCommon,
|
|
289
|
+
"structured-combined": formatCombined,
|
|
290
|
+
"structured-common": formatCommon,
|
|
291
|
+
"morgan-combined": formatMorganCombined,
|
|
292
|
+
"morgan-common": formatMorganCommon,
|
|
221
293
|
dev: formatDev,
|
|
222
294
|
short: formatShort,
|
|
223
295
|
tiny: formatTiny
|
|
@@ -285,7 +357,7 @@ function honoLogger(options = {}) {
|
|
|
285
357
|
const category = normalizeCategory(options.category ?? ["hono"]);
|
|
286
358
|
const logger = getLogger(category);
|
|
287
359
|
const level = options.level ?? "info";
|
|
288
|
-
const formatOption = options.format ?? "combined";
|
|
360
|
+
const formatOption = options.format ?? "structured-combined";
|
|
289
361
|
const skip = options.skip ?? (() => false);
|
|
290
362
|
const logRequest = options.logRequest ?? false;
|
|
291
363
|
const contextOptions = normalizeRequestContextOptions(options.context);
|
package/dist/mod.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mod.js","names":["options: boolean | RequestContextOptions | undefined","options: boolean | RequestIdOptions | undefined","value: string","c: HonoContext","options: RequestIdOptions","responseHeader","responseTime: number","resolvedRequestId: ResolvedRequestId | undefined","include: readonly RequestContextField[]","context: Record<string, unknown>","options: RequestContextOptions","requestContext: HonoRequestContextState","result: string | Record<string, unknown>","predefinedFormats: Record<PredefinedFormat, FormatFunction>","category: string | readonly string[]","options: HonoLogTapeOptions","formatFn: FormatFunction","requestContextState: HonoRequestContextState","requestContextState","result"],"sources":["../src/mod.ts"],"sourcesContent":["import { getLogger, type LogLevel, withContext } from \"@logtape/logtape\";\nimport { createMiddleware } from \"hono/factory\";\nimport type { Context, MiddlewareHandler } from \"hono\";\n\nexport type { LogLevel } from \"@logtape/logtape\";\n\n/**\n * Hono context interface exposed to custom formatters and skip callbacks.\n *\n * This matches the actual runtime object passed to the middleware, so custom\n * formatters can access context variables via methods like `c.get()` when\n * needed.\n * @since 1.3.0\n */\n// deno-lint-ignore no-explicit-any\nexport interface HonoContext extends Context<any, any, any> {}\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 c The Hono context 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 c: HonoContext,\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 /** 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 /** User-Agent header value */\n userAgent: string | undefined;\n /** Referrer header value */\n referrer: string | undefined;\n}\n\n/**\n * Request fields that can be added to the implicit request context.\n * @since 2.2.0\n */\nexport type RequestContextField =\n | \"requestId\"\n | \"method\"\n | \"url\"\n | \"path\"\n | \"userAgent\"\n | \"remoteAddr\"\n | \"referrer\";\n\n/**\n * Options for extracting, generating, and propagating a request ID.\n * @since 2.2.0\n */\nexport interface RequestIdOptions {\n /**\n * The property name used in implicit context and request log records.\n * @default \"requestId\"\n */\n readonly property?: string;\n\n /**\n * Incoming request headers to inspect in order.\n * @default [\"x-request-id\"]\n */\n readonly headerNames?: readonly string[];\n\n /**\n * Response header that receives the resolved request ID.\n * Set to `false` to disable response header propagation.\n * @default \"x-request-id\"\n */\n readonly responseHeader?: string | false;\n\n /**\n * Generates a request ID when no incoming header is present.\n * @default crypto.randomUUID()\n */\n readonly generate?: () => string;\n\n /**\n * Normalizes an incoming request ID. Return `null` to reject the value and\n * keep looking for another header or generate a new ID.\n */\n readonly normalize?: (value: string) => string | null;\n}\n\n/**\n * Options for request-scoped implicit context.\n * @since 2.2.0\n */\nexport interface RequestContextOptions {\n /**\n * Enables request ID extraction, generation, and response propagation.\n * @default true\n */\n readonly requestId?: boolean | RequestIdOptions;\n\n /**\n * Fields to add to the implicit context.\n * @default [\"requestId\"]\n */\n readonly include?: readonly RequestContextField[];\n\n /**\n * Adds application-specific fields to the implicit request context.\n */\n readonly enrich?: (\n c: HonoContext,\n ) => Record<string, unknown> | Promise<Record<string, unknown>>;\n}\n\n/**\n * Options for configuring the Hono LogTape middleware.\n * @since 1.3.0\n */\nexport interface HonoLogTapeOptions {\n /**\n * The LogTape category to use for logging.\n * @default [\"hono\"]\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(honoLogger({\n * skip: (c) => c.req.path === \"/health\",\n * }));\n * ```\n *\n * @default () => false\n */\n readonly skip?: (c: HonoContext) => 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 * Enables request-scoped implicit context and request ID correlation.\n *\n * When set to `true`, the middleware reads the `x-request-id` header,\n * generates one when it is absent, writes it to the `x-request-id` response\n * header, and adds `requestId` to all LogTape records emitted while handling\n * the request.\n *\n * @default false\n * @since 2.2.0\n */\n readonly context?: boolean | RequestContextOptions;\n}\n\nconst defaultRequestIdHeader = \"x-request-id\";\n\ninterface ResolvedRequestId {\n readonly property: string;\n readonly value: string;\n readonly responseHeader?: string;\n}\n\ninterface HonoRequestContextState {\n readonly context: Record<string, unknown>;\n readonly responseHeader?: {\n readonly name: string;\n readonly value: string;\n };\n}\n\n/**\n * Normalize request context options.\n */\nfunction normalizeRequestContextOptions(\n options: boolean | RequestContextOptions | undefined,\n): RequestContextOptions | undefined {\n if (options === true) return {};\n if (options === false || options == null) return undefined;\n return options;\n}\n\n/**\n * Normalize request ID options.\n */\nfunction normalizeRequestIdOptions(\n options: boolean | RequestIdOptions | undefined,\n): RequestIdOptions | undefined {\n if (options === false) return undefined;\n if (options === true || options == null) return {};\n return options;\n}\n\n/**\n * Generate a request ID with Web Crypto when possible.\n */\nfunction generateRequestId(): string {\n if (typeof globalThis.crypto?.randomUUID === \"function\") {\n return globalThis.crypto.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * Normalize an incoming request ID.\n */\nfunction defaultNormalizeRequestId(value: string): string | null {\n const trimmed = value.trim();\n return trimmed === \"\" ? null : trimmed;\n}\n\n/**\n * Resolve the request ID for a request.\n */\nfunction resolveRequestId(\n c: HonoContext,\n options: RequestIdOptions,\n): ResolvedRequestId {\n const property = options.property ?? \"requestId\";\n const normalize = options.normalize ?? defaultNormalizeRequestId;\n const headerNames = options.headerNames ?? [defaultRequestIdHeader];\n for (const headerName of headerNames) {\n const headerValue = c.req.header(headerName);\n if (headerValue == null) continue;\n const normalized = normalize(headerValue);\n if (normalized != null) {\n const responseHeader = options.responseHeader ?? defaultRequestIdHeader;\n return {\n property,\n value: normalized,\n responseHeader: responseHeader === false ? undefined : responseHeader,\n };\n }\n }\n const generated = (options.generate ?? generateRequestId)();\n const responseHeader = options.responseHeader ?? defaultRequestIdHeader;\n return {\n property,\n value: generated,\n responseHeader: responseHeader === false ? undefined : responseHeader,\n };\n}\n\n/**\n * Get referrer from request headers.\n */\nfunction getReferrer(c: HonoContext): string | undefined {\n return c.req.header(\"referrer\") || c.req.header(\"referer\");\n}\n\n/**\n * Get user agent from request headers.\n */\nfunction getUserAgent(c: HonoContext): string | undefined {\n return c.req.header(\"user-agent\");\n}\n\n/**\n * Get remote address from X-Forwarded-For header.\n */\nfunction getRemoteAddr(c: HonoContext): string | undefined {\n const forwarded = c.req.header(\"x-forwarded-for\");\n if (forwarded == null) return undefined;\n const firstIp = forwarded.split(\",\")[0].trim();\n return firstIp || undefined;\n}\n\n/**\n * Get content length from response headers.\n */\nfunction getContentLength(c: HonoContext): string | undefined {\n const contentLength = c.res.headers.get(\"content-length\");\n if (contentLength === null) return undefined;\n return contentLength;\n}\n\n/**\n * Build structured log properties from context.\n */\nfunction buildProperties(\n c: HonoContext,\n responseTime: number,\n): RequestLogProperties {\n return {\n method: c.req.method,\n url: c.req.url,\n path: c.req.path,\n status: c.res.status,\n responseTime,\n contentLength: getContentLength(c),\n userAgent: getUserAgent(c),\n referrer: getReferrer(c),\n };\n}\n\n/**\n * Build request context fields from a request.\n */\nfunction buildIncludedContext(\n c: HonoContext,\n resolvedRequestId: ResolvedRequestId | undefined,\n include: readonly RequestContextField[],\n): Record<string, unknown> {\n const context: Record<string, unknown> = {};\n for (const field of include) {\n switch (field) {\n case \"requestId\":\n if (resolvedRequestId != null) {\n context[resolvedRequestId.property] = resolvedRequestId.value;\n }\n break;\n case \"method\":\n context.method = c.req.method;\n break;\n case \"url\":\n context.url = c.req.url;\n break;\n case \"path\":\n context.path = c.req.path;\n break;\n case \"userAgent\":\n context.userAgent = getUserAgent(c);\n break;\n case \"remoteAddr\":\n context.remoteAddr = getRemoteAddr(c);\n break;\n case \"referrer\":\n context.referrer = getReferrer(c);\n break;\n }\n }\n return context;\n}\n\n/**\n * Build the implicit context for a request.\n */\nasync function buildRequestContext(\n c: HonoContext,\n options: RequestContextOptions,\n): Promise<HonoRequestContextState> {\n const requestIdOptions = normalizeRequestIdOptions(options.requestId);\n const resolvedRequestId = requestIdOptions == null\n ? undefined\n : resolveRequestId(c, requestIdOptions);\n const include = options.include ??\n (resolvedRequestId == null ? [] : [\"requestId\"] as const);\n const context = buildIncludedContext(c, resolvedRequestId, include);\n if (options.enrich != null) Object.assign(context, await options.enrich(c));\n const responseHeader = resolvedRequestId?.responseHeader == null\n ? undefined\n : {\n name: resolvedRequestId.responseHeader,\n value: resolvedRequestId.value,\n };\n return { context, responseHeader };\n}\n\n/**\n * Apply deferred context response headers to the final Hono response.\n */\nfunction applyResponseHeaders(\n c: HonoContext,\n requestContext: HonoRequestContextState,\n): void {\n if (requestContext.responseHeader == null) return;\n try {\n c.header(\n requestContext.responseHeader.name,\n requestContext.responseHeader.value,\n );\n } catch {\n // Keep logging middleware from replacing the application's response.\n }\n}\n\n/**\n * Add request context fields to a request log result.\n */\nfunction withRequestLogContext(\n result: string | Record<string, unknown>,\n context: Record<string, unknown>,\n): string | Record<string, unknown> {\n if (typeof result === \"string\") return result;\n return { ...result, ...context };\n}\n\n/**\n * Combined format (Apache Combined Log Format).\n * Returns all structured properties.\n */\nfunction formatCombined(\n c: HonoContext,\n responseTime: number,\n): Record<string, unknown> {\n return { ...buildProperties(c, responseTime) };\n}\n\n/**\n * Common format (Apache Common Log Format).\n * Like combined but without referrer and userAgent.\n */\nfunction formatCommon(\n c: HonoContext,\n responseTime: number,\n): Record<string, unknown> {\n const props = buildProperties(c, 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(\n c: HonoContext,\n responseTime: number,\n): string {\n const contentLength = getContentLength(c) ?? \"-\";\n return `${c.req.method} ${c.req.path} ${c.res.status} ${\n responseTime.toFixed(3)\n } ms - ${contentLength}`;\n}\n\n/**\n * Short format.\n * :method :url :status :res[content-length] - :response-time ms\n */\nfunction formatShort(\n c: HonoContext,\n responseTime: number,\n): string {\n const contentLength = getContentLength(c) ?? \"-\";\n return `${c.req.method} ${c.req.url} ${c.res.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(\n c: HonoContext,\n responseTime: number,\n): string {\n const contentLength = getContentLength(c) ?? \"-\";\n return `${c.req.method} ${c.req.path} ${c.res.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 * Creates Hono 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 { Hono } from \"hono\";\n * import { configure, getConsoleSink } from \"@logtape/logtape\";\n * import { honoLogger } from \"@logtape/hono\";\n *\n * await configure({\n * sinks: { console: getConsoleSink() },\n * loggers: [\n * { category: [\"hono\"], sinks: [\"console\"], lowestLevel: \"info\" }\n * ],\n * });\n *\n * const app = new Hono();\n * app.use(honoLogger());\n *\n * app.get(\"/\", (c) => c.json({ hello: \"world\" }));\n *\n * export default app;\n * ```\n *\n * @example With custom options\n * ```typescript\n * app.use(honoLogger({\n * category: [\"myapp\", \"http\"],\n * level: \"debug\",\n * format: \"dev\",\n * skip: (c) => c.req.path === \"/health\",\n * }));\n * ```\n *\n * @example With custom format function\n * ```typescript\n * app.use(honoLogger({\n * format: (c, responseTime) => ({\n * method: c.req.method,\n * path: c.req.path,\n * status: c.res.status,\n * duration: responseTime,\n * }),\n * }));\n * ```\n *\n * @param options Configuration options for the middleware.\n * @returns Hono middleware function.\n * @since 1.3.0\n */\nexport function honoLogger(\n options: HonoLogTapeOptions = {},\n): MiddlewareHandler {\n const category = normalizeCategory(options.category ?? [\"hono\"]);\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 contextOptions = normalizeRequestContextOptions(options.context);\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 createMiddleware(async (c, next) => {\n const startTime = Date.now();\n const honoContext = c as unknown as HonoContext;\n\n const handleRequest = async (\n requestContextState: HonoRequestContextState,\n ): Promise<void> => {\n const requestContext = requestContextState.context;\n applyResponseHeaders(honoContext, requestContextState);\n // For immediate logging, log when request arrives\n if (logRequest) {\n if (!skip(honoContext)) {\n const result = withRequestLogContext(\n formatFn(honoContext, 0),\n requestContext,\n );\n if (typeof result === \"string\") {\n logMethod(result, requestContext);\n } else {\n logMethod(\"{method} {url}\", result);\n }\n }\n await next();\n applyResponseHeaders(honoContext, requestContextState);\n return;\n }\n\n // Log after response is sent\n await next();\n applyResponseHeaders(honoContext, requestContextState);\n\n if (skip(honoContext)) return;\n\n const responseTime = Date.now() - startTime;\n const result = withRequestLogContext(\n formatFn(honoContext, responseTime),\n requestContext,\n );\n\n if (typeof result === \"string\") {\n logMethod(result, requestContext);\n } else {\n logMethod(\"{method} {url} {status} - {responseTime} ms\", result);\n }\n };\n\n if (contextOptions == null) {\n await handleRequest({ context: {} });\n return;\n }\n\n const requestContextState = await buildRequestContext(\n honoContext,\n contextOptions,\n );\n await withContext(\n requestContextState.context,\n () => handleRequest(requestContextState),\n );\n });\n}\n"],"mappings":";;;;AA8MA,MAAM,yBAAyB;;;;AAmB/B,SAAS,+BACPA,SACmC;AACnC,KAAI,YAAY,KAAM,QAAO,CAAE;AAC/B,KAAI,YAAY,SAAS,WAAW,KAAM;AAC1C,QAAO;AACR;;;;AAKD,SAAS,0BACPC,SAC8B;AAC9B,KAAI,YAAY,MAAO;AACvB,KAAI,YAAY,QAAQ,WAAW,KAAM,QAAO,CAAE;AAClD,QAAO;AACR;;;;AAKD,SAAS,oBAA4B;AACnC,YAAW,WAAW,QAAQ,eAAe,WAC3C,QAAO,WAAW,OAAO,YAAY;AAEvC,SAAQ,EAAE,KAAK,KAAK,CAAC,SAAS,GAAG,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAE,CAAC;AAC1E;;;;AAKD,SAAS,0BAA0BC,OAA8B;CAC/D,MAAM,UAAU,MAAM,MAAM;AAC5B,QAAO,YAAY,KAAK,OAAO;AAChC;;;;AAKD,SAAS,iBACPC,GACAC,SACmB;CACnB,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,YAAY,QAAQ,aAAa;CACvC,MAAM,cAAc,QAAQ,eAAe,CAAC,sBAAuB;AACnE,MAAK,MAAM,cAAc,aAAa;E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BAAiB,+BAA+B,QAAQ,QAAQ;CAGtE,MAAMC,kBAAkC,iBAAiB,WACrD,kBAAkB,gBAClB;CAEJ,MAAM,YAAY,OAAO,OAAO,KAAK,OAAO;AAE5C,QAAO,iBAAiB,OAAO,GAAG,SAAS;EACzC,MAAM,YAAY,KAAK,KAAK;EAC5B,MAAM,cAAc;EAEpB,MAAM,gBAAgB,OACpBC,0BACkB;GAClB,MAAM,iBAAiBC,sBAAoB;AAC3C,wBAAqB,aAAaA,sBAAoB;AAEtD,OAAI,YAAY;AACd,SAAK,KAAK,YAAY,EAAE;KACtB,MAAMC,WAAS,sBACb,SAAS,aAAa,EAAE,EACxB,eACD;AACD,gBAAWA,aAAW,SACpB,WAAUA,UAAQ,eAAe;SAEjC,WAAU,kBAAkBA,SAAO;IAEtC;AACD,UAAM,MAAM;AACZ,yBAAqB,aAAaD,sBAAoB;AACtD;GACD;AAGD,SAAM,MAAM;AACZ,wBAAqB,aAAaA,sBAAoB;AAEtD,OAAI,KAAK,YAAY,CAAE;GAEvB,MAAM,eAAe,KAAK,KAAK,GAAG;GAClC,MAAM,SAAS,sBACb,SAAS,aAAa,aAAa,EACnC,eACD;AAED,cAAW,WAAW,SACpB,WAAU,QAAQ,eAAe;OAEjC,WAAU,+CAA+C,OAAO;EAEnE;AAED,MAAI,kBAAkB,MAAM;AAC1B,SAAM,cAAc,EAAE,SAAS,CAAE,EAAE,EAAC;AACpC;EACD;EAED,MAAM,sBAAsB,MAAM,oBAChC,aACA,eACD;AACD,QAAM,YACJ,oBAAoB,SACpB,MAAM,cAAc,oBAAoB,CACzC;CACF,EAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"mod.js","names":["options: boolean | RequestContextOptions | undefined","options: boolean | RequestIdOptions | undefined","value: string","c: HonoContext","options: RequestIdOptions","responseHeader","responseTime: number","resolvedRequestId: ResolvedRequestId | undefined","include: readonly RequestContextField[]","context: Record<string, unknown>","options: RequestContextOptions","requestContext: HonoRequestContextState","result: string | Record<string, unknown>","value: number","timestamp: number","value: unknown","escapeSpaces: boolean","predefinedFormats: Record<PredefinedFormat, FormatFunction>","category: string | readonly string[]","options: HonoLogTapeOptions","formatFn: FormatFunction","requestContextState: HonoRequestContextState","requestContextState","result"],"sources":["../src/mod.ts"],"sourcesContent":["import { getLogger, type LogLevel, withContext } from \"@logtape/logtape\";\nimport { createMiddleware } from \"hono/factory\";\nimport type { Context, MiddlewareHandler } from \"hono\";\n\nexport type { LogLevel } from \"@logtape/logtape\";\n\n/**\n * Hono context interface exposed to custom formatters and skip callbacks.\n *\n * This matches the actual runtime object passed to the middleware, so custom\n * formatters can access context variables via methods like `c.get()` when\n * needed.\n * @since 1.3.0\n */\n// deno-lint-ignore no-explicit-any\nexport interface HonoContext extends Context<any, any, any> {}\n\n/**\n * Predefined log format names.\n * @since 1.3.0\n */\nexport type PredefinedFormat =\n /**\n * @deprecated Use `\"structured-combined\"` instead.\n */\n | \"combined\"\n /**\n * @deprecated Use `\"structured-common\"` instead.\n */\n | \"common\"\n | \"structured-combined\"\n | \"structured-common\"\n | \"morgan-combined\"\n | \"morgan-common\"\n | \"dev\"\n | \"short\"\n | \"tiny\";\n\n/**\n * Custom format function for request logging.\n *\n * @param c The Hono context 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 c: HonoContext,\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 /** 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 /** User-Agent header value */\n userAgent: string | undefined;\n /** Referrer header value */\n referrer: string | undefined;\n}\n\n/**\n * Request fields that can be added to the implicit request context.\n * @since 2.2.0\n */\nexport type RequestContextField =\n | \"requestId\"\n | \"method\"\n | \"url\"\n | \"path\"\n | \"userAgent\"\n | \"remoteAddr\"\n | \"referrer\";\n\n/**\n * Options for extracting, generating, and propagating a request ID.\n * @since 2.2.0\n */\nexport interface RequestIdOptions {\n /**\n * The property name used in implicit context and request log records.\n * @default \"requestId\"\n */\n readonly property?: string;\n\n /**\n * Incoming request headers to inspect in order.\n * @default [\"x-request-id\"]\n */\n readonly headerNames?: readonly string[];\n\n /**\n * Response header that receives the resolved request ID.\n * Set to `false` to disable response header propagation.\n * @default \"x-request-id\"\n */\n readonly responseHeader?: string | false;\n\n /**\n * Generates a request ID when no incoming header is present.\n * @default crypto.randomUUID()\n */\n readonly generate?: () => string;\n\n /**\n * Normalizes an incoming request ID. Return `null` to reject the value and\n * keep looking for another header or generate a new ID.\n */\n readonly normalize?: (value: string) => string | null;\n}\n\n/**\n * Options for request-scoped implicit context.\n * @since 2.2.0\n */\nexport interface RequestContextOptions {\n /**\n * Enables request ID extraction, generation, and response propagation.\n * @default true\n */\n readonly requestId?: boolean | RequestIdOptions;\n\n /**\n * Fields to add to the implicit context.\n * @default [\"requestId\"]\n */\n readonly include?: readonly RequestContextField[];\n\n /**\n * Adds application-specific fields to the implicit request context.\n */\n readonly enrich?: (\n c: HonoContext,\n ) => Record<string, unknown> | Promise<Record<string, unknown>>;\n}\n\n/**\n * Options for configuring the Hono LogTape middleware.\n * @since 1.3.0\n */\nexport interface HonoLogTapeOptions {\n /**\n * The LogTape category to use for logging.\n * @default [\"hono\"]\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 * Structured formats:\n * - `\"structured-combined\"` - Structured request properties (default)\n * - `\"structured-common\"` - Structured request properties without\n * referrer/userAgent\n * - `\"combined\"` - Deprecated alias for `\"structured-combined\"`\n * - `\"common\"` - Deprecated alias for `\"structured-common\"`\n *\n * Text formats:\n * - `\"morgan-combined\"` - Morgan-compatible combined access log (string)\n * - `\"morgan-common\"` - Morgan-compatible common access log (string)\n * - `\"dev\"` - Concise colored output for development (string)\n * - `\"short\"` - Shorter than common (string)\n * - `\"tiny\"` - Minimal output (string)\n *\n * @default \"structured-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(honoLogger({\n * skip: (c) => c.req.path === \"/health\",\n * }));\n * ```\n *\n * @default () => false\n */\n readonly skip?: (c: HonoContext) => 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 * Enables request-scoped implicit context and request ID correlation.\n *\n * When set to `true`, the middleware reads the `x-request-id` header,\n * generates one when it is absent, writes it to the `x-request-id` response\n * header, and adds `requestId` to all LogTape records emitted while handling\n * the request.\n *\n * @default false\n * @since 2.2.0\n */\n readonly context?: boolean | RequestContextOptions;\n}\n\nconst defaultRequestIdHeader = \"x-request-id\";\n\ninterface ResolvedRequestId {\n readonly property: string;\n readonly value: string;\n readonly responseHeader?: string;\n}\n\ninterface HonoRequestContextState {\n readonly context: Record<string, unknown>;\n readonly responseHeader?: {\n readonly name: string;\n readonly value: string;\n };\n}\n\n/**\n * Normalize request context options.\n */\nfunction normalizeRequestContextOptions(\n options: boolean | RequestContextOptions | undefined,\n): RequestContextOptions | undefined {\n if (options === true) return {};\n if (options === false || options == null) return undefined;\n return options;\n}\n\n/**\n * Normalize request ID options.\n */\nfunction normalizeRequestIdOptions(\n options: boolean | RequestIdOptions | undefined,\n): RequestIdOptions | undefined {\n if (options === false) return undefined;\n if (options === true || options == null) return {};\n return options;\n}\n\n/**\n * Generate a request ID with Web Crypto when possible.\n */\nfunction generateRequestId(): string {\n if (typeof globalThis.crypto?.randomUUID === \"function\") {\n return globalThis.crypto.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * Normalize an incoming request ID.\n */\nfunction defaultNormalizeRequestId(value: string): string | null {\n const trimmed = value.trim();\n return trimmed === \"\" ? null : trimmed;\n}\n\n/**\n * Resolve the request ID for a request.\n */\nfunction resolveRequestId(\n c: HonoContext,\n options: RequestIdOptions,\n): ResolvedRequestId {\n const property = options.property ?? \"requestId\";\n const normalize = options.normalize ?? defaultNormalizeRequestId;\n const headerNames = options.headerNames ?? [defaultRequestIdHeader];\n for (const headerName of headerNames) {\n const headerValue = c.req.header(headerName);\n if (headerValue == null) continue;\n const normalized = normalize(headerValue);\n if (normalized != null) {\n const responseHeader = options.responseHeader ?? defaultRequestIdHeader;\n return {\n property,\n value: normalized,\n responseHeader: responseHeader === false ? undefined : responseHeader,\n };\n }\n }\n const generated = (options.generate ?? generateRequestId)();\n const responseHeader = options.responseHeader ?? defaultRequestIdHeader;\n return {\n property,\n value: generated,\n responseHeader: responseHeader === false ? undefined : responseHeader,\n };\n}\n\n/**\n * Get referrer from request headers.\n */\nfunction getReferrer(c: HonoContext): string | undefined {\n return c.req.header(\"referrer\") || c.req.header(\"referer\");\n}\n\n/**\n * Get user agent from request headers.\n */\nfunction getUserAgent(c: HonoContext): string | undefined {\n return c.req.header(\"user-agent\");\n}\n\n/**\n * Get remote address from X-Forwarded-For header.\n */\nfunction getRemoteAddr(c: HonoContext): string | undefined {\n const forwarded = c.req.header(\"x-forwarded-for\");\n if (forwarded == null) return undefined;\n const firstIp = forwarded.split(\",\")[0].trim();\n return firstIp || undefined;\n}\n\n/**\n * Get content length from response headers.\n */\nfunction getContentLength(c: HonoContext): string | undefined {\n const contentLength = c.res.headers.get(\"content-length\");\n if (contentLength === null) return undefined;\n return contentLength;\n}\n\n/**\n * Build structured log properties from context.\n */\nfunction buildProperties(\n c: HonoContext,\n responseTime: number,\n): RequestLogProperties {\n return {\n method: c.req.method,\n url: c.req.url,\n path: c.req.path,\n status: c.res.status,\n responseTime,\n contentLength: getContentLength(c),\n userAgent: getUserAgent(c),\n referrer: getReferrer(c),\n };\n}\n\n/**\n * Build request context fields from a request.\n */\nfunction buildIncludedContext(\n c: HonoContext,\n resolvedRequestId: ResolvedRequestId | undefined,\n include: readonly RequestContextField[],\n): Record<string, unknown> {\n const context: Record<string, unknown> = {};\n for (const field of include) {\n switch (field) {\n case \"requestId\":\n if (resolvedRequestId != null) {\n context[resolvedRequestId.property] = resolvedRequestId.value;\n }\n break;\n case \"method\":\n context.method = c.req.method;\n break;\n case \"url\":\n context.url = c.req.url;\n break;\n case \"path\":\n context.path = c.req.path;\n break;\n case \"userAgent\":\n context.userAgent = getUserAgent(c);\n break;\n case \"remoteAddr\":\n context.remoteAddr = getRemoteAddr(c);\n break;\n case \"referrer\":\n context.referrer = getReferrer(c);\n break;\n }\n }\n return context;\n}\n\n/**\n * Build the implicit context for a request.\n */\nasync function buildRequestContext(\n c: HonoContext,\n options: RequestContextOptions,\n): Promise<HonoRequestContextState> {\n const requestIdOptions = normalizeRequestIdOptions(options.requestId);\n const resolvedRequestId = requestIdOptions == null\n ? undefined\n : resolveRequestId(c, requestIdOptions);\n const include = options.include ??\n (resolvedRequestId == null ? [] : [\"requestId\"] as const);\n const context = buildIncludedContext(c, resolvedRequestId, include);\n if (options.enrich != null) Object.assign(context, await options.enrich(c));\n const responseHeader = resolvedRequestId?.responseHeader == null\n ? undefined\n : {\n name: resolvedRequestId.responseHeader,\n value: resolvedRequestId.value,\n };\n return { context, responseHeader };\n}\n\n/**\n * Apply deferred context response headers to the final Hono response.\n */\nfunction applyResponseHeaders(\n c: HonoContext,\n requestContext: HonoRequestContextState,\n): void {\n if (requestContext.responseHeader == null) return;\n try {\n c.header(\n requestContext.responseHeader.name,\n requestContext.responseHeader.value,\n );\n } catch {\n // Keep logging middleware from replacing the application's response.\n }\n}\n\n/**\n * Add request context fields to a request log result.\n */\nfunction withRequestLogContext(\n result: string | Record<string, unknown>,\n context: Record<string, unknown>,\n): string | Record<string, unknown> {\n if (typeof result === \"string\") return result;\n return { ...result, ...context };\n}\n\nconst clfMonths = [\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n] as const;\n\nfunction pad2(value: number): string {\n return value.toString().padStart(2, \"0\");\n}\n\nfunction formatClfDate(timestamp: number = Date.now()): string {\n const date = new Date(timestamp);\n return `${pad2(date.getUTCDate())}/${\n clfMonths[date.getUTCMonth()]\n }/${date.getUTCFullYear()}:${pad2(date.getUTCHours())}:${\n pad2(date.getUTCMinutes())\n }:${pad2(date.getUTCSeconds())} +0000`;\n}\n\nfunction escapeAccessLogValue(value: unknown, escapeSpaces: boolean): string {\n const escaped = String(value)\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"')\n .replace(/\\r/g, \"\\\\r\")\n .replace(/\\n/g, \"\\\\n\")\n .replace(/\\t/g, \"\\\\t\");\n return escapeSpaces ? escaped.replace(/ /g, \"\\\\x20\") : escaped;\n}\n\nfunction formatAccessLogToken(value: unknown): string {\n if (value == null || value === \"\") return \"-\";\n return escapeAccessLogValue(value, true);\n}\n\nfunction formatAccessLogQuotedToken(value: unknown): string {\n if (value == null || value === \"\") return '\"-\"';\n return `\"${escapeAccessLogValue(value, false)}\"`;\n}\n\nfunction getRemoteUser(c: HonoContext): string | undefined {\n const authorization = c.req.header(\"authorization\");\n if (authorization == null) return undefined;\n const match = /^Basic\\s+(.+)$/i.exec(authorization);\n if (match == null || typeof globalThis.atob !== \"function\") {\n return undefined;\n }\n try {\n const decoded = globalThis.atob(match[1]);\n const colonIndex = decoded.indexOf(\":\");\n const user = colonIndex < 0 ? decoded : decoded.slice(0, colonIndex);\n return user === \"\" ? undefined : user;\n } catch {\n return undefined;\n }\n}\n\nfunction getRequestTarget(c: HonoContext): string {\n const url = new URL(c.req.url, \"http://localhost\");\n return `${url.pathname}${url.search}`;\n}\n\n/**\n * Structured combined format.\n * Returns all structured properties.\n */\nfunction formatCombined(\n c: HonoContext,\n responseTime: number,\n): Record<string, unknown> {\n return { ...buildProperties(c, responseTime) };\n}\n\n/**\n * Structured common format.\n * Like structured combined but without referrer and userAgent.\n */\nfunction formatCommon(\n c: HonoContext,\n responseTime: number,\n): Record<string, unknown> {\n const props = buildProperties(c, responseTime);\n const { referrer: _referrer, userAgent: _userAgent, ...rest } = props;\n return rest;\n}\n\n/**\n * Morgan combined format.\n * :remote-addr - :remote-user [:date[clf]]\n * \":method :url HTTP/:http-version\" :status :res[content-length]\n * \":referrer\" \":user-agent\"\n */\nfunction formatMorganCombined(c: HonoContext): string {\n return `${formatAccessLogToken(getRemoteAddr(c))} - ${\n formatAccessLogToken(getRemoteUser(c))\n } [${formatClfDate()}] \"${formatAccessLogToken(c.req.method)} ${\n formatAccessLogToken(getRequestTarget(c))\n } HTTP/-\" ${formatAccessLogToken(c.res.status)} ${\n formatAccessLogToken(getContentLength(c))\n } ${formatAccessLogQuotedToken(getReferrer(c))} ${\n formatAccessLogQuotedToken(getUserAgent(c))\n }`;\n}\n\n/**\n * Morgan common format.\n * :remote-addr - :remote-user [:date[clf]]\n * \":method :url HTTP/:http-version\" :status :res[content-length]\n */\nfunction formatMorganCommon(c: HonoContext): string {\n return `${formatAccessLogToken(getRemoteAddr(c))} - ${\n formatAccessLogToken(getRemoteUser(c))\n } [${formatClfDate()}] \"${formatAccessLogToken(c.req.method)} ${\n formatAccessLogToken(getRequestTarget(c))\n } HTTP/-\" ${formatAccessLogToken(c.res.status)} ${\n formatAccessLogToken(getContentLength(c))\n }`;\n}\n\n/**\n * Dev format (colored output for development).\n * :method :path :status :response-time ms - :res[content-length]\n */\nfunction formatDev(\n c: HonoContext,\n responseTime: number,\n): string {\n const contentLength = getContentLength(c) ?? \"-\";\n return `${c.req.method} ${c.req.path} ${c.res.status} ${\n responseTime.toFixed(3)\n } ms - ${contentLength}`;\n}\n\n/**\n * Short format.\n * :method :url :status :res[content-length] - :response-time ms\n */\nfunction formatShort(\n c: HonoContext,\n responseTime: number,\n): string {\n const contentLength = getContentLength(c) ?? \"-\";\n return `${c.req.method} ${c.req.url} ${c.res.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(\n c: HonoContext,\n responseTime: number,\n): string {\n const contentLength = getContentLength(c) ?? \"-\";\n return `${c.req.method} ${c.req.path} ${c.res.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 \"structured-combined\": formatCombined,\n \"structured-common\": formatCommon,\n \"morgan-combined\": formatMorganCombined,\n \"morgan-common\": formatMorganCommon,\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 Hono 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 { Hono } from \"hono\";\n * import { configure, getConsoleSink } from \"@logtape/logtape\";\n * import { honoLogger } from \"@logtape/hono\";\n *\n * await configure({\n * sinks: { console: getConsoleSink() },\n * loggers: [\n * { category: [\"hono\"], sinks: [\"console\"], lowestLevel: \"info\" }\n * ],\n * });\n *\n * const app = new Hono();\n * app.use(honoLogger());\n *\n * app.get(\"/\", (c) => c.json({ hello: \"world\" }));\n *\n * export default app;\n * ```\n *\n * @example With custom options\n * ```typescript\n * app.use(honoLogger({\n * category: [\"myapp\", \"http\"],\n * level: \"debug\",\n * format: \"dev\",\n * skip: (c) => c.req.path === \"/health\",\n * }));\n * ```\n *\n * @example With custom format function\n * ```typescript\n * app.use(honoLogger({\n * format: (c, responseTime) => ({\n * method: c.req.method,\n * path: c.req.path,\n * status: c.res.status,\n * duration: responseTime,\n * }),\n * }));\n * ```\n *\n * @param options Configuration options for the middleware.\n * @returns Hono middleware function.\n * @since 1.3.0\n */\nexport function honoLogger(\n options: HonoLogTapeOptions = {},\n): MiddlewareHandler {\n const category = normalizeCategory(options.category ?? [\"hono\"]);\n const logger = getLogger(category);\n const level = options.level ?? \"info\";\n const formatOption = options.format ?? \"structured-combined\";\n const skip = options.skip ?? (() => false);\n const logRequest = options.logRequest ?? false;\n const contextOptions = normalizeRequestContextOptions(options.context);\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 createMiddleware(async (c, next) => {\n const startTime = Date.now();\n const honoContext = c as unknown as HonoContext;\n\n const handleRequest = async (\n requestContextState: HonoRequestContextState,\n ): Promise<void> => {\n const requestContext = requestContextState.context;\n applyResponseHeaders(honoContext, requestContextState);\n // For immediate logging, log when request arrives\n if (logRequest) {\n if (!skip(honoContext)) {\n const result = withRequestLogContext(\n formatFn(honoContext, 0),\n requestContext,\n );\n if (typeof result === \"string\") {\n logMethod(result, requestContext);\n } else {\n logMethod(\"{method} {url}\", result);\n }\n }\n await next();\n applyResponseHeaders(honoContext, requestContextState);\n return;\n }\n\n // Log after response is sent\n await next();\n applyResponseHeaders(honoContext, requestContextState);\n\n if (skip(honoContext)) return;\n\n const responseTime = Date.now() - startTime;\n const result = withRequestLogContext(\n formatFn(honoContext, responseTime),\n requestContext,\n );\n\n if (typeof result === \"string\") {\n logMethod(result, requestContext);\n } else {\n logMethod(\"{method} {url} {status} - {responseTime} ms\", result);\n }\n };\n\n if (contextOptions == null) {\n await handleRequest({ context: {} });\n return;\n }\n\n const requestContextState = await buildRequestContext(\n honoContext,\n contextOptions,\n );\n await withContext(\n requestContext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AAK,GAAG;GAClC,MAAM,SAAS,sBACb,SAAS,aAAa,aAAa,EACnC,eACD;AAED,cAAW,WAAW,SACpB,WAAU,QAAQ,eAAe;OAEjC,WAAU,+CAA+C,OAAO;EAEnE;AAED,MAAI,kBAAkB,MAAM;AAC1B,SAAM,cAAc,EAAE,SAAS,CAAE,EAAE,EAAC;AACpC;EACD;EAED,MAAM,sBAAsB,MAAM,oBAChC,aACA,eACD;AACD,QAAM,YACJ,oBAAoB,SACpB,MAAM,cAAc,oBAAoB,CACzC;CACF,EAAC;AACH"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@logtape/hono",
|
|
3
|
-
"version": "2.2.0-dev.
|
|
3
|
+
"version": "2.2.0-dev.767+7533e10c",
|
|
4
4
|
"description": "Hono adapter for LogTape logging library",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"logging",
|
|
@@ -55,7 +55,7 @@
|
|
|
55
55
|
],
|
|
56
56
|
"peerDependencies": {
|
|
57
57
|
"hono": "^4.0.0",
|
|
58
|
-
"@logtape/logtape": "^2.2.0-dev.
|
|
58
|
+
"@logtape/logtape": "^2.2.0-dev.767+7533e10c"
|
|
59
59
|
},
|
|
60
60
|
"devDependencies": {
|
|
61
61
|
"@alinea/suite": "^0.6.3",
|