Generate Cloudflare Worker types
mainTo generate or synchronize TypeScript types based on your Worker configuration, run the following command:
npm run cf-typegenrepository·main·Indexed 40 days ago
https://github.com/maou-shonen/hono-pinoA 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.
To generate or synchronize TypeScript types based on your Worker configuration, run the following command:
npm run cf-typegenTo 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 pinonpm install hono-pino pinoIntegrate 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("");
});To start the development server for the Cloudflare Workers Vite example, use the following commands:
npm installnpm run devnpm install
npm run devTo deploy the project to Cloudflare Workers, run:
npm run deployFor 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
}),
},
}),
})
);When using Hono in a Cloudflare Workers environment, you should pass CloudflareBindings as a generic to the Hono constructor to ensure type safety for your environment bindings.
// src/index.ts
const app = new Hono<{ Bindings: CloudflareBindings }>()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,
}),
})
);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
}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.
| Option | Type | Default | Description |
|---|---|---|---|
levelFormatter | LevelFormatter | defaultLevelFormatter | Function to format the log level label (e.g., for color or custom style). |
colorEnabled | boolean | undefined (auto-detect) | - true: always use color. - false: never use color. - undefined: auto-detect. |
messageKey | string | "msg" | The key for the log message in the log object. |
requestKey | string | "req" | The key for the request object in the log object. |
responseKey | string | "res" | The key for the response object in the log object. |
levelLabelMap | Record<number, string> | pino.levels.labels | Map of log level numbers to their string labels. |
normalLogFormat | string | "[{time}] {levelLabel} - {msg}" | Format string for normal logs. Placeholders: {time}, {levelLabel}, {msg}. |
httpLogFormat | string | "[{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}. |
timeFormatter | TimeFormatter | defaultTimeFormatter | Function to format the time value for display. |
bindingsFormatter | BindingsFormatter | defaultBindingsFormat | Function to format the context (bindings) for display. |
printer | (...data: any[]) => void | console.log | Function to print the final log output. |
The pinoLogger middleware provides extensive configuration for HTTP-specific logging via the http property in the Options object.
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.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");
});