Skip to content

使用以下方式监控 Hono API 初始

🌐 Monitoring Hono APIs with Apitally

Apitally 是一个用于 REST API 的简单 API 监控和分析工具。它通过轻量级的中间件与 Hono 集成,并提供干净、直观的仪表盘,其中默认包含指标、日志和警报。

使用 Apitally,你可以:

🌐 With Apitally, you can:

  • 监控 API 使用情况、性能和错误
  • 跟踪各个用户的 API 使用情况
  • 记录并检查 API 请求和响应
  • 捕获应用日志和跟踪,并与请求相关联
  • 设置正常运行时间监控和自定义警报

安装

🌐 Installation

在你的项目中安装 Apitally SDK

🌐 Install the Apitally SDK in your project:

bash
# npm
npm install apitally

# yarn
yarn add apitally

# pnpm
pnpm add apitally

# bun
bun add apitally

设置

🌐 Setup

首先,在 Apitally 仪表板 中创建一个应用以获取你的客户端 ID。然后使用 useApitally 函数将中间件添加到你的 Hono 应用中:

🌐 First, create an app in the Apitally dashboard to get your client ID. Then add the middleware to your Hono application using the useApitally function:

ts
import { Hono } from 'hono'
import { useApitally } from 'apitally/hono'

const app = new Hono()

useApitally(app, {
  clientId: 'your-client-id', // Get this from the Apitally dashboard
  env: 'dev', // or "prod", etc.

  // Optional: Enable and configure request logging
  requestLogging: {
    enabled: true,
    logRequestHeaders: true,
    logRequestBody: true,
    logResponseBody: true,
    captureLogs: true,
  },
})

// Add your routes after the middleware
app.get('/', (c) => c.text('Hello Hono!'))

export default app

在任何其他中间件之前添加 APItally 中间件,以确保它封装了整个应用堆栈。

🌐 Add the Apitally middleware before any other middleware to ensure it wraps the entire application stack.

识别消费者

🌐 Identify consumers

要按个别消费者跟踪 API 使用情况,请使用 setConsumer 函数将请求与消费者标识符关联。这通常在身份验证后的中间件中完成。你还可以提供可选的显示名称和消费者组。

🌐 To track API usage by individual consumers, use the setConsumer function to associate requests with consumer identifiers. This is typically done in a middleware after authentication. You can also provide an optional display name and consumer group.

ts
import { setConsumer } from 'apitally/hono'

app.use(async (c, next) => {
  const payload = c.get('jwtPayload')
  if (payload) {
    setConsumer(c, {
      identifier: payload.sub,
      name: payload.name, // optional
      group: payload.group, // optional
    })
  }
  await next()
})

Apitally 中的“消费者”仪表板现在将显示所有消费者,你可以按消费者筛选日志和指标。

🌐 The Consumers dashboard in Apitally will now show all consumers and you can filter logs and metrics by consumer.

另请参阅

🌐 See also

Hono 中文网 - 粤ICP备13048890号