Skip to content

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

¥Monitoring Hono APIs with Apitally

Apitally 是一款简洁的 REST API 监控和分析工具。它通过轻量级中间件与 Hono 集成,并提供简洁直观的仪表盘,开箱即用,包含指标、日志和警报。

¥Apitally is a simple API monitoring and analytics tool for REST APIs. It integrates with Hono via a lightweight middleware and provides clean, intuitive dashboards with metrics, logs, and alerts out of the box.

使用 Apitally,你可以:

¥With Apitally, you can:

  • 监控 API 使用情况、性能和错误

    ¥Monitor API usage, performance, and errors

  • 跟踪各个用户的 API 使用情况

    ¥Track API adoption by individual consumers

  • 记录并检查请求和响应

    ¥Log and inspect requests and responses

  • 捕获应用日志,并将其与请求关联

    ¥Capture application logs, correlated with requests

  • 设置正常运行时间监控和自定义警报

    ¥Set up uptime monitoring and custom alerts

[!重要] 目前尚不支持 AWS Lambda 或 Cloudflare Workers 等无服务器平台。

¥[!IMPORTANT] Apitally currently doesn't work on serverless platforms like AWS Lambda or Cloudflare Workers.

安装

¥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 v4.11 中文网 - 粤ICP备13048890号