feat(api): Add response logging

This commit is contained in:
Jesse Wierzbinski 2024-09-04 22:52:43 +02:00
parent b5411c01e4
commit 5d2aa82247
No known key found for this signature in database
4 changed files with 37 additions and 2 deletions

View file

@ -458,3 +458,24 @@ export const debugRequest = async (req: Request) => {
logger.debug`${urlAndMethod}`;
}
};
export const debugResponse = async (res: Response) => {
const body = await res.clone().text();
const logger = getLogger("server");
const status = `${chalk.bold("Status")}: ${chalk.green(res.status)}`;
const headers = `${chalk.bold("Headers")}:\n${Array.from(
res.headers.entries(),
)
.map(([key, value]) => ` - ${chalk.cyan(key)}: ${chalk.white(value)}`)
.join("\n")}`;
const bodyLog = `${chalk.bold("Body")}: ${chalk.gray(body)}`;
if (config.logging.log_requests_verbose) {
logger.debug`${status}\n${headers}\n${bodyLog}`;
} else {
logger.debug`${status}`;
}
};

View file

@ -1,6 +1,7 @@
import type { OpenAPIHono } from "@hono/zod-openapi";
import type { Config } from "~/packages/config-manager/config.type";
import type { HonoEnv } from "~/types/api";
import { debugResponse } from "./api";
export const createServer = (config: Config, app: OpenAPIHono<HonoEnv>) =>
Bun.serve({
@ -17,7 +18,13 @@ export const createServer = (config: Config, app: OpenAPIHono<HonoEnv>) =>
}
: undefined,
hostname: config.http.bind || "0.0.0.0", // defaults to "0.0.0.0"
fetch(req, server) {
return app.fetch(req, { ip: server.requestIP(req) });
async fetch(req, server) {
const output = await app.fetch(req, { ip: server.requestIP(req) });
if (config.logging.log_responses) {
await debugResponse(output.clone());
}
return output;
},
});