Skip to content

Commit

Permalink
feat: Response message can be overridden (#27)
Browse files Browse the repository at this point in the history
  • Loading branch information
maou-shonen authored Oct 21, 2024
1 parent b47eac4 commit 62d89d9
Show file tree
Hide file tree
Showing 5 changed files with 90 additions and 3 deletions.
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,13 @@ bun add hono-pino pino
## Usage

```ts
import { Hono } from 'hono'
import { pinoLogger } from 'hono-pino'

const app = new Hono()
.use(
pinoLogger({
pino: {level: 'debug'}
pino: {level: "debug"}
}),
)
.get((c) => {
Expand All @@ -42,6 +45,9 @@ const app = new Hono()
const posts = getPosts();
logger.assign({ posts });


logger.setResMessage("Get posts success"); // optional

return c.text("");
});

Expand All @@ -55,7 +61,7 @@ await app.request("/", {
{"level":20, "token":"Bearer token"}
{
"level": 30,
"msg": "Request completed",
"msg": "Get posts success",
"user": {
"id": 1,
"name": "john"
Expand Down
10 changes: 10 additions & 0 deletions src/logger.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,4 +93,14 @@ describe("logger", () => {
b: { c: 4, d: 3, e: 5 },
});
});

it("set response message", () => {
logger.setResMessage("foo");
expect(logger.resMessage).toBe("foo");
});

it("set response level", () => {
logger.setResLevel("trace");
expect(logger.resLevel).toBe("trace");
});
});
16 changes: 16 additions & 0 deletions src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ export class PinoLogger {
#rootLogger: pino.Logger;
// Use the _ prefix to indicate that this should not be used
_logger: pino.Logger;
resMessage?: string | null;
resLevel?: pino.Level | null;

constructor(rootLogger: pino.Logger) {
this.#rootLogger = rootLogger.child({});
Expand Down Expand Up @@ -52,6 +54,20 @@ export class PinoLogger {

this._logger = this.#rootLogger.child(newBindings);
}

/**
* Override response log message
*/
setResMessage(message: string | null) {
this.resMessage = message;
}

/**
* Override response log level
*/
setResLevel(level: pino.Level | null) {
this.resLevel = level;
}
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand Down
51 changes: 51 additions & 0 deletions src/middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { pinoLogger } from "./middleware";
import type { Options } from "./types";
import { pino } from "pino";
import { PinoLogger } from "./logger";
import defu from "defu";

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

Expand Down Expand Up @@ -187,6 +188,56 @@ describe("on response", () => {
msg: "foo",
});
});

it("Override response log message", async () => {
const { logs, app } = createMockApp();
app.get("/override-message", async (c) => {
c.get("logger").setResMessage("foo");
return c.text("ok");
});

const res = await app.request("/override-message");
expect(res.status).toBe(200);
expect(res.text()).resolves.toBe("ok");

expect(logs).toHaveLength(1);
expect(logs[0]).toMatchObject(
defu(
{
req: {
url: "/override-message",
},
msg: "foo",
},
defaultResLog,
),
);
});

it("Override response log level", async () => {
const { logs, app } = createMockApp();
app.get("/override-level", async (c) => {
c.get("logger").setResLevel("debug");
return c.text("ok");
});

const res = await app.request("/override-level");
expect(res.status).toBe(200);
expect(res.text()).resolves.toBe("ok");

expect(logs).toHaveLength(1);
expect(logs[0]).toMatchObject(
defu(
{
req: {
url: "/override-level",
},
level: 20,
},
defaultResLog,
),
);
});
});

describe("response time", () => {
Expand Down
6 changes: 5 additions & 1 deletion src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,12 @@ export const pinoLogger = <ContextKey extends string = "logger">(
};
bindings = defu(bindings, onResBindings);

const level = opts?.http?.onResLevel?.(c) ?? (c.error ? "error" : "info");
const level =
logger.resLevel ??
opts?.http?.onResLevel?.(c) ??
(c.error ? "error" : "info");
const msg =
logger.resMessage ??
opts?.http?.onResMessage?.(c) ??
(c.error ? c.error.message : "Request completed");
logger[level](bindings, msg);
Expand Down

0 comments on commit 62d89d9

Please sign in to comment.