@logtape/hono 1.3.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright 2024–2025 Hong Minhee
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,121 @@
1
+ <!-- deno-fmt-ignore-file -->
2
+
3
+ @logtape/hono
4
+ =============
5
+
6
+ [![JSR][JSR badge]][JSR]
7
+ [![npm][npm badge]][npm]
8
+
9
+ This package provides [Hono] middleware for HTTP request logging using
10
+ [LogTape] as the backend, as an alternative to Hono's built-in logger
11
+ middleware.
12
+
13
+ [JSR]: https://jsr.io/@logtape/hono
14
+ [JSR badge]: https://jsr.io/badges/@logtape/hono
15
+ [npm]: https://www.npmjs.com/package/@logtape/hono
16
+ [npm badge]: https://img.shields.io/npm/v/@logtape/hono?logo=npm
17
+ [Hono]: https://hono.dev/
18
+ [LogTape]: https://logtape.org/
19
+
20
+
21
+ Installation
22
+ ------------
23
+
24
+ ~~~~ sh
25
+ deno add jsr:@logtape/hono # for Deno
26
+ npm add @logtape/hono # for npm
27
+ pnpm add @logtape/hono # for pnpm
28
+ yarn add @logtape/hono # for Yarn
29
+ bun add @logtape/hono # for Bun
30
+ ~~~~
31
+
32
+
33
+ Usage
34
+ -----
35
+
36
+ ~~~~ typescript
37
+ import { Hono } from "hono";
38
+ import { configure, getConsoleSink } from "@logtape/logtape";
39
+ import { honoLogger } from "@logtape/hono";
40
+
41
+ await configure({
42
+ sinks: { console: getConsoleSink() },
43
+ loggers: [
44
+ { category: ["hono"], sinks: ["console"], lowestLevel: "info" }
45
+ ],
46
+ });
47
+
48
+ const app = new Hono();
49
+ app.use(honoLogger());
50
+
51
+ app.get("/", (c) => c.json({ hello: "world" }));
52
+
53
+ export default app;
54
+ ~~~~
55
+
56
+
57
+ Options
58
+ -------
59
+
60
+ The `honoLogger()` function accepts an optional options object:
61
+
62
+ ~~~~ typescript
63
+ app.use(honoLogger({
64
+ category: ["myapp", "http"], // Custom category (default: ["hono"])
65
+ level: "debug", // Log level (default: "info")
66
+ format: "dev", // Predefined format (default: "combined")
67
+ skip: (c) => c.req.path === "/health", // Skip logging for specific paths
68
+ logRequest: true, // Log at request start (default: false)
69
+ }));
70
+ ~~~~
71
+
72
+
73
+ Predefined formats
74
+ ------------------
75
+
76
+ The middleware supports Morgan-compatible predefined formats:
77
+
78
+ - `"combined"`: Apache Combined Log Format with all properties (default)
79
+ - `"common"`: Apache Common Log Format (without referrer/userAgent)
80
+ - `"dev"`: Concise output for development (e.g., `GET /path 200 1.234 ms - 123`)
81
+ - `"short"`: Shorter format with remote address
82
+ - `"tiny"`: Minimal output
83
+
84
+
85
+ Custom format function
86
+ ----------------------
87
+
88
+ You can also provide a custom format function:
89
+
90
+ ~~~~ typescript
91
+ app.use(honoLogger({
92
+ format: (c, responseTime) => ({
93
+ method: c.req.method,
94
+ path: c.req.path,
95
+ status: c.res.status,
96
+ duration: responseTime,
97
+ }),
98
+ }));
99
+ ~~~~
100
+
101
+
102
+ Structured logging output
103
+ -------------------------
104
+
105
+ When using the `"combined"` format (default), the middleware logs structured
106
+ data that includes:
107
+
108
+ - `method`: HTTP request method
109
+ - `url`: Request URL
110
+ - `path`: Request path
111
+ - `status`: HTTP response status code
112
+ - `responseTime`: Response time in milliseconds
113
+ - `contentLength`: Response content-length header value
114
+ - `userAgent`: User-Agent header value
115
+ - `referrer`: Referrer header value
116
+
117
+
118
+ See also
119
+ --------
120
+
121
+ For more information, see the [LogTape documentation][LogTape].
package/deno.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@logtape/hono",
3
+ "version": "1.3.0",
4
+ "license": "MIT",
5
+ "exports": "./src/mod.ts",
6
+ "exclude": [
7
+ "coverage/",
8
+ "npm/",
9
+ "dist/"
10
+ ],
11
+ "tasks": {
12
+ "build": "pnpm build",
13
+ "test": "deno test --allow-env --allow-sys --allow-net",
14
+ "test:node": {
15
+ "dependencies": [
16
+ "build"
17
+ ],
18
+ "command": "node --experimental-transform-types --test"
19
+ },
20
+ "test:bun": {
21
+ "dependencies": [
22
+ "build"
23
+ ],
24
+ "command": "bun test"
25
+ },
26
+ "test-all": {
27
+ "dependencies": [
28
+ "test",
29
+ "test:node",
30
+ "test:bun"
31
+ ]
32
+ }
33
+ }
34
+ }
@@ -0,0 +1,30 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+
23
+ //#endregion
24
+
25
+ Object.defineProperty(exports, '__toESM', {
26
+ enumerable: true,
27
+ get: function () {
28
+ return __toESM;
29
+ }
30
+ });
package/dist/mod.cjs ADDED
@@ -0,0 +1,180 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ const __logtape_logtape = require_rolldown_runtime.__toESM(require("@logtape/logtape"));
3
+ const hono_factory = require_rolldown_runtime.__toESM(require("hono/factory"));
4
+
5
+ //#region src/mod.ts
6
+ /**
7
+ * Get referrer from request headers.
8
+ */
9
+ function getReferrer(c) {
10
+ return c.req.header("referrer") || c.req.header("referer");
11
+ }
12
+ /**
13
+ * Get user agent from request headers.
14
+ */
15
+ function getUserAgent(c) {
16
+ return c.req.header("user-agent");
17
+ }
18
+ /**
19
+ * Get content length from response headers.
20
+ */
21
+ function getContentLength(c) {
22
+ const contentLength = c.res.headers.get("content-length");
23
+ if (contentLength === null) return void 0;
24
+ return contentLength;
25
+ }
26
+ /**
27
+ * Build structured log properties from context.
28
+ */
29
+ function buildProperties(c, responseTime) {
30
+ return {
31
+ method: c.req.method,
32
+ url: c.req.url,
33
+ path: c.req.path,
34
+ status: c.res.status,
35
+ responseTime,
36
+ contentLength: getContentLength(c),
37
+ userAgent: getUserAgent(c),
38
+ referrer: getReferrer(c)
39
+ };
40
+ }
41
+ /**
42
+ * Combined format (Apache Combined Log Format).
43
+ * Returns all structured properties.
44
+ */
45
+ function formatCombined(c, responseTime) {
46
+ return { ...buildProperties(c, responseTime) };
47
+ }
48
+ /**
49
+ * Common format (Apache Common Log Format).
50
+ * Like combined but without referrer and userAgent.
51
+ */
52
+ function formatCommon(c, responseTime) {
53
+ const props = buildProperties(c, responseTime);
54
+ const { referrer: _referrer, userAgent: _userAgent,...rest } = props;
55
+ return rest;
56
+ }
57
+ /**
58
+ * Dev format (colored output for development).
59
+ * :method :path :status :response-time ms - :res[content-length]
60
+ */
61
+ function formatDev(c, responseTime) {
62
+ const contentLength = getContentLength(c) ?? "-";
63
+ return `${c.req.method} ${c.req.path} ${c.res.status} ${responseTime.toFixed(3)} ms - ${contentLength}`;
64
+ }
65
+ /**
66
+ * Short format.
67
+ * :method :url :status :res[content-length] - :response-time ms
68
+ */
69
+ function formatShort(c, responseTime) {
70
+ const contentLength = getContentLength(c) ?? "-";
71
+ return `${c.req.method} ${c.req.url} ${c.res.status} ${contentLength} - ${responseTime.toFixed(3)} ms`;
72
+ }
73
+ /**
74
+ * Tiny format (minimal output).
75
+ * :method :path :status :res[content-length] - :response-time ms
76
+ */
77
+ function formatTiny(c, responseTime) {
78
+ const contentLength = getContentLength(c) ?? "-";
79
+ return `${c.req.method} ${c.req.path} ${c.res.status} ${contentLength} - ${responseTime.toFixed(3)} ms`;
80
+ }
81
+ /**
82
+ * Map of predefined format functions.
83
+ */
84
+ const predefinedFormats = {
85
+ combined: formatCombined,
86
+ common: formatCommon,
87
+ dev: formatDev,
88
+ short: formatShort,
89
+ tiny: formatTiny
90
+ };
91
+ /**
92
+ * Normalize category to array format.
93
+ */
94
+ function normalizeCategory(category) {
95
+ return typeof category === "string" ? [category] : category;
96
+ }
97
+ /**
98
+ * Creates Hono middleware for HTTP request logging using LogTape.
99
+ *
100
+ * This middleware provides Morgan-compatible request logging with LogTape
101
+ * as the backend, supporting structured logging and customizable formats.
102
+ *
103
+ * @example Basic usage
104
+ * ```typescript
105
+ * import { Hono } from "hono";
106
+ * import { configure, getConsoleSink } from "@logtape/logtape";
107
+ * import { honoLogger } from "@logtape/hono";
108
+ *
109
+ * await configure({
110
+ * sinks: { console: getConsoleSink() },
111
+ * loggers: [
112
+ * { category: ["hono"], sinks: ["console"], lowestLevel: "info" }
113
+ * ],
114
+ * });
115
+ *
116
+ * const app = new Hono();
117
+ * app.use(honoLogger());
118
+ *
119
+ * app.get("/", (c) => c.json({ hello: "world" }));
120
+ *
121
+ * export default app;
122
+ * ```
123
+ *
124
+ * @example With custom options
125
+ * ```typescript
126
+ * app.use(honoLogger({
127
+ * category: ["myapp", "http"],
128
+ * level: "debug",
129
+ * format: "dev",
130
+ * skip: (c) => c.req.path === "/health",
131
+ * }));
132
+ * ```
133
+ *
134
+ * @example With custom format function
135
+ * ```typescript
136
+ * app.use(honoLogger({
137
+ * format: (c, responseTime) => ({
138
+ * method: c.req.method,
139
+ * path: c.req.path,
140
+ * status: c.res.status,
141
+ * duration: responseTime,
142
+ * }),
143
+ * }));
144
+ * ```
145
+ *
146
+ * @param options Configuration options for the middleware.
147
+ * @returns Hono middleware function.
148
+ * @since 1.3.0
149
+ */
150
+ function honoLogger(options = {}) {
151
+ const category = normalizeCategory(options.category ?? ["hono"]);
152
+ const logger = (0, __logtape_logtape.getLogger)(category);
153
+ const level = options.level ?? "info";
154
+ const formatOption = options.format ?? "combined";
155
+ const skip = options.skip ?? (() => false);
156
+ const logRequest = options.logRequest ?? false;
157
+ const formatFn = typeof formatOption === "string" ? predefinedFormats[formatOption] : formatOption;
158
+ const logMethod = logger[level].bind(logger);
159
+ return (0, hono_factory.createMiddleware)(async (c, next) => {
160
+ const startTime = Date.now();
161
+ if (logRequest) {
162
+ if (!skip(c)) {
163
+ const result$1 = formatFn(c, 0);
164
+ if (typeof result$1 === "string") logMethod(result$1);
165
+ else logMethod("{method} {url}", result$1);
166
+ }
167
+ await next();
168
+ return;
169
+ }
170
+ await next();
171
+ if (skip(c)) return;
172
+ const responseTime = Date.now() - startTime;
173
+ const result = formatFn(c, responseTime);
174
+ if (typeof result === "string") logMethod(result);
175
+ else logMethod("{method} {url} {status} - {responseTime} ms", result);
176
+ });
177
+ }
178
+
179
+ //#endregion
180
+ exports.honoLogger = honoLogger;
package/dist/mod.d.cts ADDED
@@ -0,0 +1,171 @@
1
+ import { LogLevel, LogLevel as LogLevel$1 } from "@logtape/logtape";
2
+ import { MiddlewareHandler } from "hono";
3
+
4
+ //#region src/mod.d.ts
5
+
6
+ /**
7
+ * Minimal Hono Context interface for compatibility across Hono versions.
8
+ * @since 1.3.0
9
+ */
10
+ interface HonoContext {
11
+ req: {
12
+ method: string;
13
+ url: string;
14
+ path: string;
15
+ header(name: string): string | undefined;
16
+ };
17
+ res: {
18
+ status: number;
19
+ headers: {
20
+ get(name: string): string | null;
21
+ };
22
+ };
23
+ }
24
+ /**
25
+ * Predefined log format names compatible with Morgan.
26
+ * @since 1.3.0
27
+ */
28
+ type PredefinedFormat = "combined" | "common" | "dev" | "short" | "tiny";
29
+ /**
30
+ * Custom format function for request logging.
31
+ *
32
+ * @param c The Hono context object.
33
+ * @param responseTime The response time in milliseconds.
34
+ * @returns A string message or an object with structured properties.
35
+ * @since 1.3.0
36
+ */
37
+ type FormatFunction = (c: HonoContext, responseTime: number) => string | Record<string, unknown>;
38
+ /**
39
+ * Structured log properties for HTTP requests.
40
+ * @since 1.3.0
41
+ */
42
+ interface RequestLogProperties {
43
+ /** HTTP request method */
44
+ method: string;
45
+ /** Request URL */
46
+ url: string;
47
+ /** Request path */
48
+ path: string;
49
+ /** HTTP response status code */
50
+ status: number;
51
+ /** Response time in milliseconds */
52
+ responseTime: number;
53
+ /** Response content-length header value */
54
+ contentLength: string | undefined;
55
+ /** User-Agent header value */
56
+ userAgent: string | undefined;
57
+ /** Referrer header value */
58
+ referrer: string | undefined;
59
+ }
60
+ /**
61
+ * Options for configuring the Hono LogTape middleware.
62
+ * @since 1.3.0
63
+ */
64
+ interface HonoLogTapeOptions {
65
+ /**
66
+ * The LogTape category to use for logging.
67
+ * @default ["hono"]
68
+ */
69
+ readonly category?: string | readonly string[];
70
+ /**
71
+ * The log level to use for request logging.
72
+ * @default "info"
73
+ */
74
+ readonly level?: LogLevel$1;
75
+ /**
76
+ * The format for log output.
77
+ * Can be a predefined format name or a custom format function.
78
+ *
79
+ * Predefined formats:
80
+ * - `"combined"` - Apache Combined Log Format (structured, default)
81
+ * - `"common"` - Apache Common Log Format (structured, no referrer/userAgent)
82
+ * - `"dev"` - Concise colored output for development (string)
83
+ * - `"short"` - Shorter than common (string)
84
+ * - `"tiny"` - Minimal output (string)
85
+ *
86
+ * @default "combined"
87
+ */
88
+ readonly format?: PredefinedFormat | FormatFunction;
89
+ /**
90
+ * Function to determine whether logging should be skipped.
91
+ * Return `true` to skip logging for a request.
92
+ *
93
+ * @example Skip logging for health check endpoint
94
+ * ```typescript
95
+ * app.use(honoLogger({
96
+ * skip: (c) => c.req.path === "/health",
97
+ * }));
98
+ * ```
99
+ *
100
+ * @default () => false
101
+ */
102
+ readonly skip?: (c: HonoContext) => boolean;
103
+ /**
104
+ * If `true`, logs are written immediately when the request is received.
105
+ * If `false` (default), logs are written after the response is sent.
106
+ *
107
+ * Note: When `logRequest` is `true`, response-related properties
108
+ * (status, responseTime, contentLength) will not be available.
109
+ *
110
+ * @default false
111
+ */
112
+ readonly logRequest?: boolean;
113
+ }
114
+ /**
115
+ * Creates Hono middleware for HTTP request logging using LogTape.
116
+ *
117
+ * This middleware provides Morgan-compatible request logging with LogTape
118
+ * as the backend, supporting structured logging and customizable formats.
119
+ *
120
+ * @example Basic usage
121
+ * ```typescript
122
+ * import { Hono } from "hono";
123
+ * import { configure, getConsoleSink } from "@logtape/logtape";
124
+ * import { honoLogger } from "@logtape/hono";
125
+ *
126
+ * await configure({
127
+ * sinks: { console: getConsoleSink() },
128
+ * loggers: [
129
+ * { category: ["hono"], sinks: ["console"], lowestLevel: "info" }
130
+ * ],
131
+ * });
132
+ *
133
+ * const app = new Hono();
134
+ * app.use(honoLogger());
135
+ *
136
+ * app.get("/", (c) => c.json({ hello: "world" }));
137
+ *
138
+ * export default app;
139
+ * ```
140
+ *
141
+ * @example With custom options
142
+ * ```typescript
143
+ * app.use(honoLogger({
144
+ * category: ["myapp", "http"],
145
+ * level: "debug",
146
+ * format: "dev",
147
+ * skip: (c) => c.req.path === "/health",
148
+ * }));
149
+ * ```
150
+ *
151
+ * @example With custom format function
152
+ * ```typescript
153
+ * app.use(honoLogger({
154
+ * format: (c, responseTime) => ({
155
+ * method: c.req.method,
156
+ * path: c.req.path,
157
+ * status: c.res.status,
158
+ * duration: responseTime,
159
+ * }),
160
+ * }));
161
+ * ```
162
+ *
163
+ * @param options Configuration options for the middleware.
164
+ * @returns Hono middleware function.
165
+ * @since 1.3.0
166
+ */
167
+ declare function honoLogger(options?: HonoLogTapeOptions): MiddlewareHandler;
168
+ //# sourceMappingURL=mod.d.ts.map
169
+ //#endregion
170
+ export { FormatFunction, HonoContext, HonoLogTapeOptions, LogLevel, PredefinedFormat, RequestLogProperties, honoLogger };
171
+ //# sourceMappingURL=mod.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.d.cts","names":[],"sources":["../src/mod.ts"],"sourcesContent":[],"mappings":";;;;;;AAUA;AAmBA;AAUA;AAA0B,UA7BT,WAAA,CA6BS;EAAA,GACrB,EAAA;IAES,MAAA,EAAA,MAAA;IAAM,GAAA,EAAA,MAAA;IAMH,IAAA,EAAA,MAAA;IAuBA,MAAA,CAAA,IAAA,EAAA,MAAkB,CAAA,EAAA,MAAA,GAAA,SAAA;EAAA,CAAA;EAAA,GAWhB,EAAA;IAeC,MAAA,EAAA,MAAA;IAAmB,OAAA,EAAA;MAejB,GAAA,CAAA,IAAA,EAAA,MAAA,CAAA,EAAA,MAAA,GAAA,IAAA;IAAW,CAAA;EAmMjB,CAAA;;;;AAEI;;KAxRR,gBAAA;;;;;;;;;KAUA,cAAA,OACP,+CAES;;;;;UAMG,oBAAA;;;;;;;;;;;;;;;;;;;;;;UAuBA,kBAAA;;;;;;;;;;mBAWE;;;;;;;;;;;;;;oBAeC,mBAAmB;;;;;;;;;;;;;;sBAejB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAmMN,UAAA,WACL,qBACR"}