-
Notifications
You must be signed in to change notification settings - Fork 308
feat(structured-logger): add @hono/structured-logger middleware #1782
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
gabry-ts
wants to merge
6
commits into
honojs:main
Choose a base branch
from
gabry-ts:feat/structured-logger
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
ef60b84
feat(structured-logger): add @hono/structured-logger middleware
gabry-ts 1c4c808
feat(structured-logger): address review feedback
gabry-ts cc0fa1a
chore: update yarn.lock for structured-logger
gabry-ts dee4fd0
bugfix: fix typecheck and lint errors in structured-logger
gabry-ts 678eecf
chore: address review feedback from yusukebe
gabry-ts ca5e4f2
ci: apply automated fixes
autofix-ci[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| '@hono/structured-logger': minor | ||
| --- | ||
|
|
||
| Add @hono/structured-logger middleware: library agnostic structured logging with request scoped logger on c.var.logger, automatic response time measurement, and native requestId integration. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,201 @@ | ||
| # @hono/structured-logger | ||
|
|
||
| Structured Logger middleware for [Hono](https://hono.dev). | ||
|
|
||
| Library agnostic: works with pino, winston, bunyan, console, or any logger that implements the `BaseLogger` interface. Zero dependencies. Provides a request scoped logger on `c.var.logger` with full type safety, automatic response time measurement, and native integration with `hono/request-id`. | ||
|
|
||
| ## Install | ||
|
|
||
| ```bash | ||
| npm install @hono/structured-logger | ||
| ``` | ||
|
|
||
| ## Usage | ||
|
|
||
| ### With pino | ||
|
|
||
| ```typescript | ||
| import { Hono } from 'hono' | ||
| import { requestId } from 'hono/request-id' | ||
| import { structuredLogger } from '@hono/structured-logger' | ||
| import pino from 'pino' | ||
|
|
||
| const rootLogger = pino() | ||
|
|
||
| const app = new Hono() | ||
|
|
||
| app.use(requestId()) | ||
| app.use( | ||
| structuredLogger({ | ||
| createLogger: (c) => rootLogger.child({ requestId: c.var.requestId }), | ||
| }) | ||
| ) | ||
|
|
||
| app.get('/', (c) => { | ||
| c.var.logger.info('handling request') | ||
| return c.text('Hello!') | ||
| }) | ||
| ``` | ||
|
|
||
| ### With winston | ||
|
|
||
| ```typescript | ||
| import { Hono } from 'hono' | ||
| import { structuredLogger } from '@hono/structured-logger' | ||
| import winston from 'winston' | ||
|
|
||
| const rootLogger = winston.createLogger({ /* config */ }) | ||
|
|
||
| const app = new Hono() | ||
|
|
||
| app.use( | ||
| structuredLogger({ | ||
| createLogger: (c) => rootLogger.child({ requestId: c.var.requestId }), | ||
| }) | ||
| ) | ||
| ``` | ||
|
|
||
| ### With console (development, zero deps) | ||
|
|
||
| ```typescript | ||
| import { Hono } from 'hono' | ||
| import { structuredLogger } from '@hono/structured-logger' | ||
|
|
||
| const app = new Hono() | ||
|
|
||
| app.use( | ||
| structuredLogger({ | ||
| createLogger: () => console, | ||
| }) | ||
| ) | ||
| ``` | ||
|
|
||
| ### Custom hooks | ||
|
|
||
| ```typescript | ||
| import { Hono } from 'hono' | ||
| import { structuredLogger } from '@hono/structured-logger' | ||
| import pino from 'pino' | ||
|
|
||
| const rootLogger = pino() | ||
|
|
||
| const app = new Hono() | ||
|
|
||
| app.use( | ||
| structuredLogger({ | ||
| createLogger: (c) => rootLogger.child({ requestId: c.var.requestId }), | ||
| onRequest: (logger, c) => { | ||
| logger.info( | ||
| { | ||
| method: c.req.method, | ||
| path: c.req.path, | ||
| userAgent: c.req.header('user-agent'), | ||
| }, | ||
| 'incoming request' | ||
| ) | ||
| }, | ||
| onResponse: (logger, c, elapsedMs) => { | ||
| logger.info( | ||
| { | ||
| status: c.res.status, | ||
| elapsedMs, | ||
| contentLength: c.res.headers.get('content-length'), | ||
| }, | ||
| 'request completed' | ||
| ) | ||
| }, | ||
| onError: (logger, err, c) => { | ||
| logger.error( | ||
| { | ||
| err, | ||
| method: c.req.method, | ||
| path: c.req.path, | ||
| }, | ||
| 'request failed' | ||
| ) | ||
| }, | ||
| }) | ||
| ) | ||
| ``` | ||
|
|
||
| ### Custom context key | ||
|
|
||
| If you already have a `logger` variable on your context, use `contextKey` to pick a different name: | ||
|
|
||
| ```typescript | ||
| app.use( | ||
| structuredLogger({ | ||
| createLogger: () => myLogger, | ||
| contextKey: 'log', | ||
| }) | ||
| ) | ||
|
|
||
| app.get('/', (c) => { | ||
| c.var.log.info('hello') | ||
| return c.text('ok') | ||
| }) | ||
| ``` | ||
|
|
||
| ### Type safe context | ||
|
|
||
| Declare the logger type on your Hono app for full type safety: | ||
|
|
||
| ```typescript | ||
| import type { pino } from 'pino' | ||
|
|
||
| type Env = { | ||
| Variables: { | ||
| logger: pino.Logger | ||
| } | ||
| } | ||
|
|
||
| const app = new Hono<Env>() | ||
| ``` | ||
|
|
||
| ## API | ||
|
|
||
| ### `structuredLogger(options)` | ||
|
|
||
| Returns a Hono `MiddlewareHandler`. | ||
|
|
||
| #### Options | ||
|
|
||
| | Option | Type | Required | Default | Description | | ||
| |---|---|---|---|---| | ||
| | `createLogger` | `(c: Context) => L` | Yes | | Factory that creates a request scoped logger instance | | ||
| | `contextKey` | `string` | No | `'logger'` | Key used to store the logger on `c.var` | | ||
|
||
| | `onRequest` | `(logger: L, c: Context) => void \| Promise<void>` | No | Logs method + path at info level | Called before handler execution | | ||
| | `onResponse` | `(logger: L, c: Context, elapsedMs: number) => void \| Promise<void>` | No | Logs method, path, status and elapsed time at info level | Called after handler execution | | ||
| | `onError` | `(logger: L, err: Error, c: Context) => void \| Promise<void>` | No | Logs error, method, path and status at error level | Called when handler throws | | ||
|
|
||
| ### `BaseLogger` | ||
|
|
||
| Minimal interface your logger must implement: | ||
|
|
||
| ```typescript | ||
| interface BaseLogger { | ||
| info(obj: unknown, msg?: string, ...args: unknown[]): void | ||
| warn(obj: unknown, msg?: string, ...args: unknown[]): void | ||
| error(obj: unknown, msg?: string, ...args: unknown[]): void | ||
| debug(obj: unknown, msg?: string, ...args: unknown[]): void | ||
| } | ||
| ``` | ||
|
|
||
| Compatible with pino, winston, bunyan, console, and most logging libraries out of the box. | ||
|
|
||
| ## Behavior | ||
|
|
||
| 1. `createLogger(c)` is called once per request. | ||
| 2. The logger is stored on `c.var[contextKey]`. | ||
| 3. `onRequest` fires before handler execution. | ||
| 4. After handler completes, `onResponse` fires with elapsed time in milliseconds (measured via `performance.now()`). | ||
| 5. If the handler throws, Hono's error handler runs first, then `onError` fires (checking `c.error`). `onResponse` is skipped when an error occurred. | ||
| 6. `onError` and `onResponse` are mutually exclusive per request. | ||
|
|
||
| ## Runtime compatibility | ||
|
|
||
| Works on all runtimes supported by Hono: Node.js, Deno, Bun, Cloudflare Workers, AWS Lambda, Vercel Edge, Fastly Compute. No Node specific APIs used. | ||
|
|
||
| ## License | ||
|
|
||
| MIT | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| { | ||
| "name": "@hono/structured-logger", | ||
| "version": "0.1.0", | ||
yusukebe marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| "license": "MIT", | ||
| "exports": { | ||
| ".": "./src/index.ts" | ||
| }, | ||
| "imports": { | ||
| "hono": "jsr:@hono/hono@^4.8.3" | ||
| }, | ||
| "publish": { | ||
| "include": ["deno.json", "README.md", "src/**/*.ts"], | ||
| "exclude": ["src/**/*.test.ts"] | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| { | ||
| "name": "@hono/structured-logger", | ||
| "version": "0.1.0", | ||
yusukebe marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| "description": "Structured Logger middleware for Hono", | ||
| "type": "module", | ||
| "main": "dist/index.js", | ||
| "module": "dist/index.js", | ||
| "types": "dist/index.d.ts", | ||
| "files": [ | ||
| "dist" | ||
| ], | ||
| "scripts": { | ||
| "build": "tsdown", | ||
| "format": "prettier --check . --ignore-path ../../.gitignore", | ||
| "lint": "eslint", | ||
| "typecheck": "tsc -b tsconfig.json", | ||
| "test": "vitest", | ||
| "version:jsr": "yarn version:set $npm_package_version" | ||
| }, | ||
| "exports": { | ||
| ".": { | ||
| "import": { | ||
| "types": "./dist/index.d.ts", | ||
| "default": "./dist/index.js" | ||
| }, | ||
| "require": { | ||
| "types": "./dist/index.d.cts", | ||
| "default": "./dist/index.cjs" | ||
| } | ||
| } | ||
| }, | ||
| "license": "MIT", | ||
| "publishConfig": { | ||
| "registry": "https://registry.npmjs.org", | ||
| "access": "public", | ||
| "provenance": true | ||
| }, | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "git+https://github.com/honojs/middleware.git", | ||
| "directory": "packages/structured-logger" | ||
| }, | ||
| "homepage": "https://github.com/honojs/middleware", | ||
| "peerDependencies": { | ||
| "hono": ">=4.0.0" | ||
| }, | ||
| "devDependencies": { | ||
| "hono": "^4.11.5", | ||
| "tsdown": "^0.15.9", | ||
| "typescript": "^5.9.3", | ||
| "vitest": "^4.1.0-beta.1" | ||
| }, | ||
| "engines": { | ||
| "node": ">=16.0.0" | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
How about adding the introduction for adding type support for
c.var.logger?Like this:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@gabry-ts Ahh, sorry! I missed the
Type safe contextsection you wrote. Passingpino.Loggeris better thanReturnType<typeof rootLogger.child>. My request is not necessary. Can you revert the change?