@logtape/koa 1.3.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mod.d.ts ADDED
@@ -0,0 +1,192 @@
1
+ import { LogLevel, LogLevel as LogLevel$1 } from "@logtape/logtape";
2
+
3
+ //#region src/mod.d.ts
4
+
5
+ /**
6
+ * Minimal Koa Context interface for compatibility across Koa 2.x and 3.x.
7
+ *
8
+ * This interface includes common aliases available on the Koa context object.
9
+ * See https://koajs.com/#context for the full API.
10
+ *
11
+ * @since 1.3.0
12
+ */
13
+ interface KoaContext {
14
+ /** HTTP request method (alias for ctx.request.method) */
15
+ method: string;
16
+ /** Request URL (alias for ctx.request.url) */
17
+ url: string;
18
+ /** Request pathname (alias for ctx.request.path) */
19
+ path: string;
20
+ /** HTTP response status code (alias for ctx.response.status) */
21
+ status: number;
22
+ /** Remote client IP address (alias for ctx.request.ip) */
23
+ ip: string;
24
+ /** Koa Response object */
25
+ response: {
26
+ length?: number;
27
+ };
28
+ /**
29
+ * Get a request header field value (case-insensitive).
30
+ * @param field The header field name.
31
+ * @returns The header value, or an empty string if not present.
32
+ */
33
+ get(field: string): string;
34
+ }
35
+ /**
36
+ * Koa middleware function type.
37
+ * @since 1.3.0
38
+ */
39
+ type KoaMiddleware = (ctx: KoaContext, next: () => Promise<void>) => Promise<void>;
40
+ /**
41
+ * Predefined log format names compatible with Morgan.
42
+ * @since 1.3.0
43
+ */
44
+ type PredefinedFormat = "combined" | "common" | "dev" | "short" | "tiny";
45
+ /**
46
+ * Custom format function for request logging.
47
+ *
48
+ * @param ctx The Koa context object.
49
+ * @param responseTime The response time in milliseconds.
50
+ * @returns A string message or an object with structured properties.
51
+ * @since 1.3.0
52
+ */
53
+ type FormatFunction = (ctx: KoaContext, responseTime: number) => string | Record<string, unknown>;
54
+ /**
55
+ * Structured log properties for HTTP requests.
56
+ * @since 1.3.0
57
+ */
58
+ interface RequestLogProperties {
59
+ /** HTTP request method */
60
+ method: string;
61
+ /** Request URL */
62
+ url: string;
63
+ /** Request path */
64
+ path: string;
65
+ /** HTTP response status code */
66
+ status: number;
67
+ /** Response time in milliseconds */
68
+ responseTime: number;
69
+ /** Response content-length */
70
+ contentLength: number | undefined;
71
+ /** Remote client address */
72
+ remoteAddr: string | undefined;
73
+ /** User-Agent header value */
74
+ userAgent: string | undefined;
75
+ /** Referrer header value */
76
+ referrer: string | undefined;
77
+ }
78
+ /**
79
+ * Options for configuring the Koa LogTape middleware.
80
+ * @since 1.3.0
81
+ */
82
+ interface KoaLogTapeOptions {
83
+ /**
84
+ * The LogTape category to use for logging.
85
+ * @default ["koa"]
86
+ */
87
+ readonly category?: string | readonly string[];
88
+ /**
89
+ * The log level to use for request logging.
90
+ * @default "info"
91
+ */
92
+ readonly level?: LogLevel$1;
93
+ /**
94
+ * The format for log output.
95
+ * Can be a predefined format name or a custom format function.
96
+ *
97
+ * Predefined formats:
98
+ * - `"combined"` - Apache Combined Log Format (structured, default)
99
+ * - `"common"` - Apache Common Log Format (structured, no referrer/userAgent)
100
+ * - `"dev"` - Concise colored output for development (string)
101
+ * - `"short"` - Shorter than common (string)
102
+ * - `"tiny"` - Minimal output (string)
103
+ *
104
+ * @default "combined"
105
+ */
106
+ readonly format?: PredefinedFormat | FormatFunction;
107
+ /**
108
+ * Function to determine whether logging should be skipped.
109
+ * Return `true` to skip logging for a request.
110
+ *
111
+ * @example Skip logging for health check endpoint
112
+ * ```typescript
113
+ * app.use(koaLogger({
114
+ * skip: (ctx) => ctx.path === "/health",
115
+ * }));
116
+ * ```
117
+ *
118
+ * @default () => false
119
+ */
120
+ readonly skip?: (ctx: KoaContext) => boolean;
121
+ /**
122
+ * If `true`, logs are written immediately when the request is received.
123
+ * If `false` (default), logs are written after the response is sent.
124
+ *
125
+ * Note: When `logRequest` is `true`, response-related properties
126
+ * (status, responseTime, contentLength) will not be available.
127
+ *
128
+ * @default false
129
+ */
130
+ readonly logRequest?: boolean;
131
+ }
132
+ /**
133
+ * Creates Koa middleware for HTTP request logging using LogTape.
134
+ *
135
+ * This middleware provides Morgan-compatible request logging with LogTape
136
+ * as the backend, supporting structured logging and customizable formats.
137
+ * It serves as an alternative to koa-logger with structured logging support.
138
+ *
139
+ * @example Basic usage
140
+ * ```typescript
141
+ * import Koa from "koa";
142
+ * import { configure, getConsoleSink } from "@logtape/logtape";
143
+ * import { koaLogger } from "@logtape/koa";
144
+ *
145
+ * await configure({
146
+ * sinks: { console: getConsoleSink() },
147
+ * loggers: [
148
+ * { category: ["koa"], sinks: ["console"], lowestLevel: "info" }
149
+ * ],
150
+ * });
151
+ *
152
+ * const app = new Koa();
153
+ * app.use(koaLogger());
154
+ *
155
+ * app.use((ctx) => {
156
+ * ctx.body = { hello: "world" };
157
+ * });
158
+ *
159
+ * app.listen(3000);
160
+ * ```
161
+ *
162
+ * @example With custom options
163
+ * ```typescript
164
+ * app.use(koaLogger({
165
+ * category: ["myapp", "http"],
166
+ * level: "debug",
167
+ * format: "dev",
168
+ * skip: (ctx) => ctx.path === "/health",
169
+ * }));
170
+ * ```
171
+ *
172
+ * @example With custom format function
173
+ * ```typescript
174
+ * app.use(koaLogger({
175
+ * format: (ctx, responseTime) => ({
176
+ * method: ctx.method,
177
+ * path: ctx.path,
178
+ * status: ctx.status,
179
+ * duration: responseTime,
180
+ * }),
181
+ * }));
182
+ * ```
183
+ *
184
+ * @param options Configuration options for the middleware.
185
+ * @returns Koa middleware function.
186
+ * @since 1.3.0
187
+ */
188
+ declare function koaLogger(options?: KoaLogTapeOptions): KoaMiddleware;
189
+ //# sourceMappingURL=mod.d.ts.map
190
+ //#endregion
191
+ export { FormatFunction, KoaContext, KoaLogTapeOptions, KoaMiddleware, LogLevel, PredefinedFormat, RequestLogProperties, koaLogger };
192
+ //# sourceMappingURL=mod.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.d.ts","names":[],"sources":["../src/mod.ts"],"sourcesContent":[],"mappings":";;;;;AAYA;AA2BA;;;;;AAGY;AAMA,UApCK,UAAA,CAoCW;EAUhB;EAAc,MAAA,EAAA,MAAA;EAAA;EACT,GAEH,EAAA,MAAA;EAAM;EAMH,IAAA,EAAA,MAAA;EAyBA;EAAiB,MAAA,EAAA,MAAA;EAAA;EAWP,EAAA,EAeP,MAAA;EAAgB;EAAiB,QAe7B,EAAA;IAAU,MAAA,CAAA,EAAA,MAAA;EAkNlB,CAAA;EAAS;;;AAET;;;;;;;;KAlTJ,aAAA,SACL,wBACO,kBACT;;;;;KAMO,gBAAA;;;;;;;;;KAUA,cAAA,SACL,8CAEO;;;;;UAMG,oBAAA;;;;;;;;;;;;;;;;;;;;;;;;UAyBA,iBAAA;;;;;;;;;;mBAWE;;;;;;;;;;;;;;oBAeC,mBAAmB;;;;;;;;;;;;;;wBAef;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAkNR,SAAA,WACL,oBACR"}
package/dist/mod.js ADDED
@@ -0,0 +1,193 @@
1
+ import { getLogger } from "@logtape/logtape";
2
+
3
+ //#region src/mod.ts
4
+ /**
5
+ * Get referrer from request headers.
6
+ * Returns undefined if the header is not present or empty.
7
+ */
8
+ function getReferrer(ctx) {
9
+ const referrer = ctx.get("referrer") || ctx.get("referer");
10
+ return referrer !== "" ? referrer : void 0;
11
+ }
12
+ /**
13
+ * Get user agent from request headers.
14
+ * Returns undefined if the header is not present or empty.
15
+ */
16
+ function getUserAgent(ctx) {
17
+ const userAgent = ctx.get("user-agent");
18
+ return userAgent !== "" ? userAgent : void 0;
19
+ }
20
+ /**
21
+ * Get remote address from context.
22
+ * Returns undefined if not available.
23
+ */
24
+ function getRemoteAddr(ctx) {
25
+ return ctx.ip !== "" ? ctx.ip : void 0;
26
+ }
27
+ /**
28
+ * Get content length from response.
29
+ */
30
+ function getContentLength(ctx) {
31
+ return ctx.response.length;
32
+ }
33
+ /**
34
+ * Build structured log properties from context.
35
+ */
36
+ function buildProperties(ctx, responseTime) {
37
+ return {
38
+ method: ctx.method,
39
+ url: ctx.url,
40
+ path: ctx.path,
41
+ status: ctx.status,
42
+ responseTime,
43
+ contentLength: getContentLength(ctx),
44
+ remoteAddr: getRemoteAddr(ctx),
45
+ userAgent: getUserAgent(ctx),
46
+ referrer: getReferrer(ctx)
47
+ };
48
+ }
49
+ /**
50
+ * Combined format (Apache Combined Log Format).
51
+ * Returns all structured properties.
52
+ */
53
+ function formatCombined(ctx, responseTime) {
54
+ return { ...buildProperties(ctx, responseTime) };
55
+ }
56
+ /**
57
+ * Common format (Apache Common Log Format).
58
+ * Like combined but without referrer and userAgent.
59
+ */
60
+ function formatCommon(ctx, responseTime) {
61
+ const props = buildProperties(ctx, responseTime);
62
+ const { referrer: _referrer, userAgent: _userAgent,...rest } = props;
63
+ return rest;
64
+ }
65
+ /**
66
+ * Dev format (colored output for development).
67
+ * :method :path :status :response-time ms - :res[content-length]
68
+ */
69
+ function formatDev(ctx, responseTime) {
70
+ const contentLength = getContentLength(ctx) ?? "-";
71
+ return `${ctx.method} ${ctx.path} ${ctx.status} ${responseTime.toFixed(3)} ms - ${contentLength}`;
72
+ }
73
+ /**
74
+ * Short format.
75
+ * :remote-addr :method :url :status :res[content-length] - :response-time ms
76
+ */
77
+ function formatShort(ctx, responseTime) {
78
+ const remoteAddr = getRemoteAddr(ctx) ?? "-";
79
+ const contentLength = getContentLength(ctx) ?? "-";
80
+ return `${remoteAddr} ${ctx.method} ${ctx.url} ${ctx.status} ${contentLength} - ${responseTime.toFixed(3)} ms`;
81
+ }
82
+ /**
83
+ * Tiny format (minimal output).
84
+ * :method :path :status :res[content-length] - :response-time ms
85
+ */
86
+ function formatTiny(ctx, responseTime) {
87
+ const contentLength = getContentLength(ctx) ?? "-";
88
+ return `${ctx.method} ${ctx.path} ${ctx.status} ${contentLength} - ${responseTime.toFixed(3)} ms`;
89
+ }
90
+ /**
91
+ * Map of predefined format functions.
92
+ */
93
+ const predefinedFormats = {
94
+ combined: formatCombined,
95
+ common: formatCommon,
96
+ dev: formatDev,
97
+ short: formatShort,
98
+ tiny: formatTiny
99
+ };
100
+ /**
101
+ * Normalize category to array format.
102
+ */
103
+ function normalizeCategory(category) {
104
+ return typeof category === "string" ? [category] : category;
105
+ }
106
+ /**
107
+ * Creates Koa middleware for HTTP request logging using LogTape.
108
+ *
109
+ * This middleware provides Morgan-compatible request logging with LogTape
110
+ * as the backend, supporting structured logging and customizable formats.
111
+ * It serves as an alternative to koa-logger with structured logging support.
112
+ *
113
+ * @example Basic usage
114
+ * ```typescript
115
+ * import Koa from "koa";
116
+ * import { configure, getConsoleSink } from "@logtape/logtape";
117
+ * import { koaLogger } from "@logtape/koa";
118
+ *
119
+ * await configure({
120
+ * sinks: { console: getConsoleSink() },
121
+ * loggers: [
122
+ * { category: ["koa"], sinks: ["console"], lowestLevel: "info" }
123
+ * ],
124
+ * });
125
+ *
126
+ * const app = new Koa();
127
+ * app.use(koaLogger());
128
+ *
129
+ * app.use((ctx) => {
130
+ * ctx.body = { hello: "world" };
131
+ * });
132
+ *
133
+ * app.listen(3000);
134
+ * ```
135
+ *
136
+ * @example With custom options
137
+ * ```typescript
138
+ * app.use(koaLogger({
139
+ * category: ["myapp", "http"],
140
+ * level: "debug",
141
+ * format: "dev",
142
+ * skip: (ctx) => ctx.path === "/health",
143
+ * }));
144
+ * ```
145
+ *
146
+ * @example With custom format function
147
+ * ```typescript
148
+ * app.use(koaLogger({
149
+ * format: (ctx, responseTime) => ({
150
+ * method: ctx.method,
151
+ * path: ctx.path,
152
+ * status: ctx.status,
153
+ * duration: responseTime,
154
+ * }),
155
+ * }));
156
+ * ```
157
+ *
158
+ * @param options Configuration options for the middleware.
159
+ * @returns Koa middleware function.
160
+ * @since 1.3.0
161
+ */
162
+ function koaLogger(options = {}) {
163
+ const category = normalizeCategory(options.category ?? ["koa"]);
164
+ const logger = getLogger(category);
165
+ const level = options.level ?? "info";
166
+ const formatOption = options.format ?? "combined";
167
+ const skip = options.skip ?? (() => false);
168
+ const logRequest = options.logRequest ?? false;
169
+ const formatFn = typeof formatOption === "string" ? predefinedFormats[formatOption] : formatOption;
170
+ const logMethod = logger[level].bind(logger);
171
+ return async (ctx, next) => {
172
+ const startTime = Date.now();
173
+ if (logRequest) {
174
+ if (!skip(ctx)) {
175
+ const result$1 = formatFn(ctx, 0);
176
+ if (typeof result$1 === "string") logMethod(result$1);
177
+ else logMethod("{method} {url}", result$1);
178
+ }
179
+ await next();
180
+ return;
181
+ }
182
+ await next();
183
+ if (skip(ctx)) return;
184
+ const responseTime = Date.now() - startTime;
185
+ const result = formatFn(ctx, responseTime);
186
+ if (typeof result === "string") logMethod(result);
187
+ else logMethod("{method} {url} {status} - {responseTime} ms", result);
188
+ };
189
+ }
190
+
191
+ //#endregion
192
+ export { koaLogger };
193
+ //# sourceMappingURL=mod.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.js","names":["ctx: KoaContext","responseTime: number","predefinedFormats: Record<PredefinedFormat, FormatFunction>","category: string | readonly string[]","options: KoaLogTapeOptions","formatFn: FormatFunction","next: () => Promise<void>","result"],"sources":["../src/mod.ts"],"sourcesContent":["import { getLogger, type LogLevel } from \"@logtape/logtape\";\n\nexport type { LogLevel } from \"@logtape/logtape\";\n\n/**\n * Minimal Koa Context interface for compatibility across Koa 2.x and 3.x.\n *\n * This interface includes common aliases available on the Koa context object.\n * See https://koajs.com/#context for the full API.\n *\n * @since 1.3.0\n */\nexport interface KoaContext {\n /** HTTP request method (alias for ctx.request.method) */\n method: string;\n /** Request URL (alias for ctx.request.url) */\n url: string;\n /** Request pathname (alias for ctx.request.path) */\n path: string;\n /** HTTP response status code (alias for ctx.response.status) */\n status: number;\n /** Remote client IP address (alias for ctx.request.ip) */\n ip: string;\n /** Koa Response object */\n response: {\n length?: number;\n };\n /**\n * Get a request header field value (case-insensitive).\n * @param field The header field name.\n * @returns The header value, or an empty string if not present.\n */\n get(field: string): string;\n}\n\n/**\n * Koa middleware function type.\n * @since 1.3.0\n */\nexport type KoaMiddleware = (\n ctx: KoaContext,\n next: () => Promise<void>,\n) => Promise<void>;\n\n/**\n * Predefined log format names compatible with Morgan.\n * @since 1.3.0\n */\nexport type PredefinedFormat = \"combined\" | \"common\" | \"dev\" | \"short\" | \"tiny\";\n\n/**\n * Custom format function for request logging.\n *\n * @param ctx The Koa 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 ctx: KoaContext,\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 */\n contentLength: number | undefined;\n /** Remote client address */\n remoteAddr: string | undefined;\n /** User-Agent header value */\n userAgent: string | undefined;\n /** Referrer header value */\n referrer: string | undefined;\n}\n\n/**\n * Options for configuring the Koa LogTape middleware.\n * @since 1.3.0\n */\nexport interface KoaLogTapeOptions {\n /**\n * The LogTape category to use for logging.\n * @default [\"koa\"]\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(koaLogger({\n * skip: (ctx) => ctx.path === \"/health\",\n * }));\n * ```\n *\n * @default () => false\n */\n readonly skip?: (ctx: KoaContext) => 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/**\n * Get referrer from request headers.\n * Returns undefined if the header is not present or empty.\n */\nfunction getReferrer(ctx: KoaContext): string | undefined {\n const referrer = ctx.get(\"referrer\") || ctx.get(\"referer\");\n return referrer !== \"\" ? referrer : undefined;\n}\n\n/**\n * Get user agent from request headers.\n * Returns undefined if the header is not present or empty.\n */\nfunction getUserAgent(ctx: KoaContext): string | undefined {\n const userAgent = ctx.get(\"user-agent\");\n return userAgent !== \"\" ? userAgent : undefined;\n}\n\n/**\n * Get remote address from context.\n * Returns undefined if not available.\n */\nfunction getRemoteAddr(ctx: KoaContext): string | undefined {\n return ctx.ip !== \"\" ? ctx.ip : undefined;\n}\n\n/**\n * Get content length from response.\n */\nfunction getContentLength(ctx: KoaContext): number | undefined {\n return ctx.response.length;\n}\n\n/**\n * Build structured log properties from context.\n */\nfunction buildProperties(\n ctx: KoaContext,\n responseTime: number,\n): RequestLogProperties {\n return {\n method: ctx.method,\n url: ctx.url,\n path: ctx.path,\n status: ctx.status,\n responseTime,\n contentLength: getContentLength(ctx),\n remoteAddr: getRemoteAddr(ctx),\n userAgent: getUserAgent(ctx),\n referrer: getReferrer(ctx),\n };\n}\n\n/**\n * Combined format (Apache Combined Log Format).\n * Returns all structured properties.\n */\nfunction formatCombined(\n ctx: KoaContext,\n responseTime: number,\n): Record<string, unknown> {\n return { ...buildProperties(ctx, responseTime) };\n}\n\n/**\n * Common format (Apache Common Log Format).\n * Like combined but without referrer and userAgent.\n */\nfunction formatCommon(\n ctx: KoaContext,\n responseTime: number,\n): Record<string, unknown> {\n const props = buildProperties(ctx, 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 ctx: KoaContext,\n responseTime: number,\n): string {\n const contentLength = getContentLength(ctx) ?? \"-\";\n return `${ctx.method} ${ctx.path} ${ctx.status} ${\n responseTime.toFixed(3)\n } ms - ${contentLength}`;\n}\n\n/**\n * Short format.\n * :remote-addr :method :url :status :res[content-length] - :response-time ms\n */\nfunction formatShort(\n ctx: KoaContext,\n responseTime: number,\n): string {\n const remoteAddr = getRemoteAddr(ctx) ?? \"-\";\n const contentLength = getContentLength(ctx) ?? \"-\";\n return `${remoteAddr} ${ctx.method} ${ctx.url} ${ctx.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 ctx: KoaContext,\n responseTime: number,\n): string {\n const contentLength = getContentLength(ctx) ?? \"-\";\n return `${ctx.method} ${ctx.path} ${ctx.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 Koa 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 * It serves as an alternative to koa-logger with structured logging support.\n *\n * @example Basic usage\n * ```typescript\n * import Koa from \"koa\";\n * import { configure, getConsoleSink } from \"@logtape/logtape\";\n * import { koaLogger } from \"@logtape/koa\";\n *\n * await configure({\n * sinks: { console: getConsoleSink() },\n * loggers: [\n * { category: [\"koa\"], sinks: [\"console\"], lowestLevel: \"info\" }\n * ],\n * });\n *\n * const app = new Koa();\n * app.use(koaLogger());\n *\n * app.use((ctx) => {\n * ctx.body = { hello: \"world\" };\n * });\n *\n * app.listen(3000);\n * ```\n *\n * @example With custom options\n * ```typescript\n * app.use(koaLogger({\n * category: [\"myapp\", \"http\"],\n * level: \"debug\",\n * format: \"dev\",\n * skip: (ctx) => ctx.path === \"/health\",\n * }));\n * ```\n *\n * @example With custom format function\n * ```typescript\n * app.use(koaLogger({\n * format: (ctx, responseTime) => ({\n * method: ctx.method,\n * path: ctx.path,\n * status: ctx.status,\n * duration: responseTime,\n * }),\n * }));\n * ```\n *\n * @param options Configuration options for the middleware.\n * @returns Koa middleware function.\n * @since 1.3.0\n */\nexport function koaLogger(\n options: KoaLogTapeOptions = {},\n): KoaMiddleware {\n const category = normalizeCategory(options.category ?? [\"koa\"]);\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\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 async (ctx: KoaContext, next: () => Promise<void>): Promise<void> => {\n const startTime = Date.now();\n\n // For immediate logging, log when request arrives\n if (logRequest) {\n if (!skip(ctx)) {\n const result = formatFn(ctx, 0);\n if (typeof result === \"string\") {\n logMethod(result);\n } else {\n logMethod(\"{method} {url}\", result);\n }\n }\n await next();\n return;\n }\n\n // Log after response is sent\n await next();\n\n if (skip(ctx)) return;\n\n const responseTime = Date.now() - startTime;\n const result = formatFn(ctx, responseTime);\n\n if (typeof result === \"string\") {\n logMethod(result);\n } else {\n logMethod(\"{method} {url} {status} - {responseTime} ms\", result);\n }\n };\n}\n"],"mappings":";;;;;;;AAuJA,SAAS,YAAYA,KAAqC;CACxD,MAAM,WAAW,IAAI,IAAI,WAAW,IAAI,IAAI,IAAI,UAAU;AAC1D,QAAO,aAAa,KAAK;AAC1B;;;;;AAMD,SAAS,aAAaA,KAAqC;CACzD,MA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+ "keywords": [
6
+ "logging",
7
+ "log",
8
+ "logger",
9
+ "koa",
10
+ "middleware",
11
+ "http",
12
+ "request",
13
+ "adapter",
14
+ "logtape"
15
+ ],
16
+ "license": "MIT",
17
+ "author": {
18
+ "name": "Hong Minhee",
19
+ "email": "hong@minhee.org",
20
+ "url": "https://hongminhee.org/"
21
+ },
22
+ "homepage": "https://logtape.org/",
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/dahlia/logtape.git",
26
+ "directory": "packages/koa/"
27
+ },
28
+ "bugs": {
29
+ "url": "https://github.com/dahlia/logtape/issues"
30
+ },
31
+ "funding": [
32
+ "https://github.com/sponsors/dahlia"
33
+ ],
34
+ "type": "module",
35
+ "module": "./dist/mod.js",
36
+ "main": "./dist/mod.cjs",
37
+ "types": "./dist/mod.d.ts",
38
+ "exports": {
39
+ ".": {
40
+ "types": {
41
+ "import": "./dist/mod.d.ts",
42
+ "require": "./dist/mod.d.cts"
43
+ },
44
+ "import": "./dist/mod.js",
45
+ "require": "./dist/mod.cjs"
46
+ },
47
+ "./package.json": "./package.json"
48
+ },
49
+ "sideEffects": false,
50
+ "peerDependencies": {
51
+ "koa": "^2.0.0 || ^3.0.0",
52
+ "@logtape/logtape": "^1.3.0"
53
+ },
54
+ "devDependencies": {
55
+ "@alinea/suite": "^0.6.3",
56
+ "@std/assert": "npm:@jsr/std__assert@^1.0.13",
57
+ "@types/koa": "^2.15.0",
58
+ "koa": "^2.16.1",
59
+ "tsdown": "^0.12.7",
60
+ "typescript": "^5.8.3"
61
+ },
62
+ "scripts": {
63
+ "build": "tsdown",
64
+ "prepublish": "tsdown",
65
+ "test": "tsdown && node --experimental-transform-types --test",
66
+ "test:bun": "tsdown && bun test",
67
+ "test:deno": "deno test --allow-env --allow-sys --allow-net",
68
+ "test-all": "tsdown && node --experimental-transform-types --test && bun test && deno test"
69
+ }
70
+ }