# @gatehub/microkit 中文文档

规范地址：https://npmcn.com/package/%40gatehub/microkit/

版本：0\.16\.0
npm 元数据更新时间：2026-11-13T10:50:01.943Z
中文译文更新时间：2026-11-16T00:05:25.765Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40gatehub/microkit
原文对照：https://npmcn.com/package/%40gatehub/microkit/?lang=original
项目主页：https://github.com/GateHubNet/microkit#readme
源码仓库：https://github.com/GateHubNet/microkit

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：101 kB，44 个文件
- 模块格式：CommonJS
- TypeScript 类型：未声明
- Node.js 要求：\>=24\.0\.0
- 运行依赖：17 个
- peer 依赖：@opentelemetry/api ~1\.10\.0
- 首次发布：2019-08-01T14:31:51.533Z
- 最新版本发布：2026-11-13T10:50:01.690Z
- 近 30 天下载量：2204（2026-10-16 至 2026-11-14，npm 官方下载统计）
- 已发布版本数：17（近 12 个月 14 个）

## 中文简介

公开微服务工具包

## 安装

```sh
npm install @gatehub/microkit
```

也可以使用：`pnpm add @gatehub/microkit`、`yarn add @gatehub/microkit`、`bun add @gatehub/microkit`

## README

# 微基特 [![NPM version](https://badge.fury.io/js/microkit.svg)](https://npmjs.org/package/@gatehub/microkit)

> Node.js 微服务工具包

用于微服务的抽象工具包,让节点开发者再次快乐.

## 安装

```sh
$ npm install --save @gatehub/microkit
```

## 使用量

```js
var MicroKit = require('microkit');

// Instantiate MicroKit
var microkit = new MicroKit({
  name: 'myAwesomeService',
  environment: 'production',
  logLevel: 'info',
  catchGlobal: true, // catch global errors
  queue: {
    name: 'amqp',
    url: "amqp://localhost",
    queue: 'myAwesomeService',
    socketOptions: {heartbeat: 5, channelMax: 100}, // optional, overrides url params; heartbeat defaults to 5, channelMax to the broker's limit; other keys (e.g. TLS ca/cert) are passed to the socket
    reconnectTimeInSeconds: 5, // optional, values <= 0 fall back to the default
    publishTimeout: 5000 // optional, ms, default for the per-publish `timeout` option; a timed out message is dropped if not yet sent, but may still be delivered if it was already awaiting the broker's confirm
  }, // queue provider config
  error: {name: 'sentry', url: "https://dd..ba:d8..35@app.getsentry.com/24343"} // error reporter config
});

/** or for development it will log on stdout
 *  var microkit = new MicroKit({name: 'myAwesomeService'});
 **/

// Logging
microkit.logger.debug('message', {key: 'value'});
microkit.logger.info('message', {key: 'value'});
microkit.logger.warn('message', {key: 'value'});
microkit.logger.fatal(new Error("some error"));
microkit.logger.error('message', {key: 'value', err: new Error("some error")});

var logger = microkit.logger.create('componentName', {some: 'context'});
logger.info('message', {key: 'value'});

// Queue
microkit.queue.publish({key: 'value'}, {some: 'data'});
microkit.queue.publish({key: {key: 'value'}, message: {key: 'value'}});
// handlers always get the message body and the event
microkit.queue.subscribe({key: 'value'}, (data, event) => {
  console.log("message", data);
  console.log("headers", event.headers);         // {key: 'value'}
  console.log("routing key", event.routingKey);  // '' for headers messages
  console.log("id", event.id);                   // headers if any, otherwise the routing key
});

// Error reporting
microkit.error.capture(new Error('some error'));

// Metrics
microkit.metrics.send('some.metric', 10, {tag1: 'value', tag2: 'value2'});

// Exit handling
microkit.onExit(() => server.close());

// Express integration (logging, error reporting)
app.use(microkit.express.preHandler); // before all middlewares
app.use(microkit.express.postHandler); // after middlewares

// config
microkit.config.get('key.value');

// common errors
const MyConnectionError = microkit.errors.ConnectionError.extend({
  name: 'MyConnectionError'
});
throw new MyConnectionError({code: 'database_error', error: err});
```

### 追踪

为了能够追踪,它需要包含在开始脚本中,以便在其他一切之前被加载:

```
    "start": "node --require @gatehub/microkit/lib/telemetry.js dist/server.js",
```

#### 配置

配置参数将从环境变量中获取. 需要以下环境变量:

```env
# The destination to send traces to
  OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=http://localhost:4318/v1/traces
# Your service name - it will be listed as such in the traces
  OTEL_SERVICE_NAME=my-service-name
# Log level - info is fine unless debugging
  OTEL_LOG_LEVEL=info
# Enable tracing database requests
  TRACING_SQL_ENABLE=true
```

对于本地和服务特定配置,需要两个配置文件:

-   `.tracing.json` : 运行时配置 `excludeRoutes` 财务报告和审定财务报表 `ignoredOutgoingHosts` (其他参数应设置为env vars)
-   `dev.tracing.json`: 本地配置(所有参数)

从环境中获取的任何配置变量都将优先于配置文件.

示例

```json
{
  "otlpEndpoint": "http://localhost:4318/v1/traces", // optional, dev 
  "otelServiceName": "service-name", // optional, dev
  "otelLogLevel": "info", // optional, dev
  "otelSqlTracingEnabled": true, // optional, dev, default false
  "otelAmqpTraceContentEnabled": true, // optional, dev, default false
  "excludeRoutes": [
    "/healthz/liveness",
    "/metricz"
  ],
  "ignoredOutgoingHosts": [
  ]
}
```

#### 使用量

任何函数都可以用 TraceSpan来附加到跟踪上. `getActiveSpan()` 可用于获得当前活动跨度. `spanObjectStringify()` 可用于将任何对象串入适当的格式.

```js
    @microkit.tracing.TraceSpan()
    public async someFunction(payload: Payload) {
        const span = microkit.tracing.getActiveSpan()
        span?.setAttribute(
            'some-attribute-name-payload',
            microkit.tracing.spanObjectStringify(payload),
        );

        ... function body
    }
```

## 许可证

麻省理工学院 [GateHub 网络](https://www.gatehub.net/)

## 常见问题

### @gatehub/microkit 是什么？

公开微服务工具包

### 如何安装 @gatehub/microkit？

在项目目录运行 npm install @gatehub/microkit，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：@opentelemetry/api（~1\.10\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @gatehub/microkit 支持 TypeScript 吗？

该包的 package\.json 没有声明类型入口。需要类型提示时，可以在 npm 上查找社区维护的 @types/gatehub\_\_microkit 是否存在。

### @gatehub/microkit 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @gatehub/microkit 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=24\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @gatehub/microkit 可以商用吗？

@gatehub/microkit 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @gatehub/microkit 的下载量有多少？

根据 npm 官方下载统计，@gatehub/microkit 在 2026/10/16 – 2026/11/14 这 30 天内被下载 2,204 次，日均约 73 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @gatehub/microkit 还在维护吗？

最新版本 0\.16\.0 发布于 2026/11/13（2 天前）；至今共发布 17 个版本，其中过去 12 个月发布了 14 个；首次发布于 2019/08/01。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

