@gatehub/microkit

中文文档
0.16.0发布于 2026/11/13MITCommonJS近 30 天下载 2204

Opiniated microservice toolkit

原始使用文档
文档目录4 节
  1. Installation
  2. Usage
  3. Tracing
  4. License

microkit NPM version

Node.js microservice toolkit

Abstraction toolkit for microservices, to make nodejs developers happy again.

Installation

$ npm install --save @gatehub/microkit

Usage

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:[email protected]/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});

Tracing

To enable tracing, it needs to be included in the start script for it to be loaded before everything else:

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

Configuration

The configuration parameters will be acquired from the environment variables. The following environment variables are required:

# 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

For local and service specific configuration two configuration files are required:

  • .tracing.json : Runtime configuration with excludeRoutes and ignoredOutgoingHosts (other parameters should be set-up as env vars)
  • dev.tracing.json: Local configuration (all parameters)

Any configuration variables that are acquired from the environment will take priority over the configuration file.

Example:

{
  "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": [
  ]
}

Usage

Any function can be annotated with TraceSpan to add it to the trace. getActiveSpan() can be used to get the current active span. spanObjectStringify() can be used to stringify any object into an appropriate format.

    @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
    }

License

MIT © GateHubNet

版本与发布记录

@gatehub/microkit 共发布 17 个版本,首次发布于 2019/08/01;过去 12 个月发布了 14 个版本。

版本发布日期距今
0.16.0latest2026/11/132 天前
0.15.12026/11/105 天前
0.15.02026/11/096 天前
0.14.12026/11/069 天前
0.13.162026/11/069 天前
0.13.152026/09/171 个月前

关于 @gatehub/microkit 的常见问题

@gatehub/microkit 是什么?

Opiniated microservice toolkit

如何安装 @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 和提交记录判断。