Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/structured-logger-init.md
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.
201 changes: 201 additions & 0 deletions packages/structured-logger/README.md
Copy link
Copy Markdown
Member

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:

import { Hono } from 'hono'
import { structuredLogger } from '@hono/structured-logger'

import pino from 'pino'

const rootLogger = pino()

const app = new Hono<{
  Variables: {
    logger: ReturnType<typeof rootLogger.child>
  }
}>()

app.use(
  structuredLogger({
    createLogger: (c) => rootLogger.child({ foo: 'bar' })
  })
)

app.get('/', (c) => {
  c.var.logger.info('hello') // typed!
  return c.json({ foo: 'bar' })
})

Copy link
Copy Markdown
Member

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 context section you wrote. Passing pino.Logger is better than ReturnType<typeof rootLogger.child>. My request is not necessary. Can you revert the change?

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` |
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would the API maybe be simpler if you merge contextKey option into createLogger? like:
createLogger: (c) => ({ logger: rootLogger.child({ requestId: c.var.requestId }) })

could maybe be more flexible, but also more verbose. But I think I prefer your approach...

| `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
15 changes: 15 additions & 0 deletions packages/structured-logger/deno.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "@hono/structured-logger",
"version": "0.1.0",
"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"]
}
}
56 changes: 56 additions & 0 deletions packages/structured-logger/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
{
"name": "@hono/structured-logger",
"version": "0.1.0",
"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"
}
}
Loading