hono-pino

repository·main·Indexed 40 days ago

https://github.com/maou-shonen/hono-pino

A Pino logger plugin for the Hono web framework providing fast, minimal-overhead logging with full Pino compatibility. It features request-scoped context bindings via the PinoLogger class, a dedicated debug-log transport for Node.js and browser environments, and middleware that injects a logger instance into the Hono context (c.var.logger). Version 0.10.3.

Tokens
5.8K
Snippets
22
Records
29
Agent score
99%

What's inside hono-pino

  1. Install hono-pino and pino

    main

    To use hono-pino, you must also install pino. Use the command corresponding to your package manager:

    # npm
    npm install hono-pino pino
    
    # pnpm
    pnpm add hono-pino pino
    
    # bun
    bun add hono-pino pino
    npm install hono-pino pino
  2. Use pinoLogger in Hono

    main

    Integrate pinoLogger as middleware in your Hono application. The logger instance is then available on the context variable c.var.logger. You can use standard Pino logging methods and use .assign() to add context (bindings) to the logger for the remainder of the request lifecycle.

    import { Hono } from 'hono'
    import { pinoLogger } from 'hono-pino'
    
    const app = new Hono()
      .use(
        pinoLogger({
          pino: {level: "debug"}
        }),
      )
      .get((c) => {
        const { logger } = c.var;
    
        const token = c.req.header("Authorization") ?? "";
        logger.debug({ token });
    
        const user = getAuthorizedUser(token);
        // Add user to all subsequent logs in this request
        logger.assign({ user });
    
        const posts = getPosts();
        // Add posts to all subsequent logs in this request
        logger.assign({ posts });
    
        // Optional: set a specific message for the response log
        logger.setResMessage("Get posts success");
    
        return c.text("");
      });
  3. Configure hono-pino/debug-log Transport (Browser)

    main

    For browser environments, use createHandler from hono-pino/debug-log and pass it to the pino.browser.write option.

    import pino from "pino";
    import { Hono } from "hono";
    import { pinoLogger } from "hono-pino";
    import { createHandler as debugLog } from "hono-pino/debug-log";
    
    const options = {}; // DebugLogOptions
    
    const app = new Hono().use(
      pinoLogger({
        pino: pino({
          level: "trace",
          browser: {
            write: debugLog({
              ...options
            }),
          },
        }),
      })
    );
  4. Configure hono-pino/debug-log Transport (Node.js)

    main

    The hono-pino/debug-log transport is a lightweight, readable transport for development. In Node.js, configure it via the transport.target option in your Pino configuration.

    import pino from "pino";
    import { Hono } from "hono";
    import { pinoLogger } from "hono-pino";
    import type { DebugLogOptions } from "hono-pino/debug-log";
    
    const options: DebugLogOptions = {
      // options...
    };
    
    const app = new Hono().use(
      pinoLogger({
        pino: pino({
          base: null,
          level: "trace",
          transport: {
            target: "hono-pino/debug-log",
            options,
          },
          timestamp: pino.stdTimeFunctions.unixTime,
        }),
      })
    );
  5. PinoLogger API Reference

    main

    The PinoLogger instance is attached to c.var.logger. It provides standard Pino logging methods and utility methods for managing request-scoped bindings.

    class PinoLogger {
      // Standard Pino log levels
      trace: pino.LogFn
      debug: pino.LogFn
      info: pino.LogFn
      warn: pino.LogFn
      error: pino.LogFn
      fatal: pino.LogFn
    
      // Context management
      bindings(): pino.Bindings
      resetBindings(): void
      assign(
        bindings: pino.Bindings,
        opts?: { deep?: boolean }
      ): void
    }
  6. Configure hono-pino/debug-log options

    main

    When using the debug-log transport, you can pass a DebugLogOptions object to customize the appearance and structure of your logs. This includes controlling color output, changing the keys used for log data, and defining custom string formats for both normal and HTTP logs.

    Available Options

    OptionTypeDefaultDescription
    levelFormatterLevelFormatterdefaultLevelFormatterFunction to format the log level label (e.g., for color or custom style).
    colorEnabledbooleanundefined (auto-detect)- true: always use color. - false: never use color. - undefined: auto-detect.
    messageKeystring"msg"The key for the log message in the log object.
    requestKeystring"req"The key for the request object in the log object.
    responseKeystring"res"The key for the response object in the log object.
    levelLabelMapRecord<number, string>pino.levels.labelsMap of log level numbers to their string labels.
    normalLogFormatstring"[{time}] {levelLabel} - {msg}"Format string for normal logs. Placeholders: {time}, {levelLabel}, {msg}.
    httpLogFormatstring"[{time}] {reqId} {req.method} {req.url} {res.status} - {msg} ({responseTime}ms)"Format string for HTTP logs. Placeholders: {time}, {reqId}, {req.method}, {req.url}, {res.status}, {responseTime}, {msg}, {bindings}.
    timeFormatterTimeFormatterdefaultTimeFormatterFunction to format the time value for display.
    bindingsFormatterBindingsFormatterdefaultBindingsFormatFunction to format the context (bindings) for display.
    printer(...data: any[]) => voidconsole.logFunction to print the final log output.
  7. Configure `pinoLogger` HTTP logging options

    main

    The pinoLogger middleware provides extensive configuration for HTTP-specific logging via the http property in the Options object.

    Key HTTP Options:

    • http: false: Disables all automatic HTTP logging.
    • onReqBindings: Function to return custom request bindings. Defaults to { req: { url, method, headers } }.
    • onReqMessage: Function to generate a custom request log message. The log level is determined by onReqLevel or defaults to info.
    • onReqLevel: Function to determine the log level for the request message.
    • reqId: A function to generate a request ID. If set to false, no reqId is added to bindings.
    • referRequestIdKey: The key in c.var to look for an existing request ID (defaults to requestId).
    • responseTime: Boolean to enable/disable response time calculation (defaults to true).
    • onResMessage: Function to generate a custom response log message. If set to false, response logging is disabled.
    • onResBindings: Function to return custom response bindings. Defaults to { res: { status, headers } }.
    • onResLevel: Function to determine the log level for the response message.
  8. Configure the `logger()` middleware options

    main

    The logger() middleware accepts an Options object to customize how the Pino logger is instantiated and how HTTP requests are logged.

    Key configuration areas include:

    • contextKey: The key used to retrieve the logger from the Hono context. Defaults to "logger".
    • pino: Defines the Pino instance, options, or a factory function to create the logger.
    • nodeRuntime: Controls runtime detection (Node/Bun vs others). Defaults to "auto".
    • http: Configuration for HTTP request/response logging. Set to false to disable HTTP logging.
    // Example: Custom context key and custom pino instance
    new Hono()
      .use(logger({
        contextKey: "myLogger" as const,
        pino: pino({ level: "info" })
      }))
      .get('/', (c) => {
        const logger = c.get("myLogger");
      });