pinojs / pino

🌲 super fast, all natural json logger
http://getpino.io
MIT License
14.16k stars 876 forks source link

How to use pino with hono #1969

Closed qoomon closed 1 month ago

qoomon commented 5 months ago

I'm using https://github.com/honojs/hono, however I'm not sure how to use pino with it.

Especially how to set and log a request trace id (X-Request-Id) for every request logger.

Can someone help me out?

mcollina commented 5 months ago

I have no clue, I've never used hono.

crebelskydico commented 2 months ago

@qoomon, I hope your issue has already been resolved. I stumbled across your issue because I'm trying to achieve the same thing.

If not, there is an ongoing project for a plugin that you may want to get involved in: https://github.com/maou-shonen/hono-pino.

The easiest solution I can think of is to write a custom logger using Pino as middleware. This way, you can ensure that all requests are handled.

import { Hono } from "hono";
import pino from "pino";

const app = new Hono();
const logger = pino();

app.use((c, next) => {
  logger.trace(`${c.req.header("X-Request-Id")}`);
  return next();
});

If you find a better solution or are working on something on top of Hono.js, please let us know.

marceloverdijk commented 1 month ago

@qoomon I'm currently using this:

import { Hono, Context } from 'hono';
import { requestId } from 'hono/request-id';

const app = new Hono();

app.use(requestId());

app.use(async (c: Context, next) => {
  c.set(
    'logger',
    pino({
      browser: {
        formatters: {
          level(label, _number) {
            return { level: label.toUpperCase() };
          },
        },
        write: (o) => {
          const { time, level, msg } = o;
          const paddedLevel = level.padEnd(5, ' ');
          const requestId = c.var.requestId;
          console.log(`[${time}] ${paddedLevel} (${requestId}): ${msg}`);
        },
      },
      enabled: true,
      level: 'debug',
      timestamp: pino.stdTimeFunctions.isoTime,
    }),
  );
}

app.get('/customers/:id', (c: Context) => {
  const id = c.req.param('id');
  c.var.logger.debug('Loading customer with id=%s', id);
  ...
})

which would output:

[2024-08-26T20:54:40.750Z] DEBUG (ec1eeec6-6dc7-45a8-872e-19d360844d80): Loading customer with id=jane-doe

Note: the requestId is set automatically by the hono/request-id middleware.

github-actions[bot] commented 2 weeks ago

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.