微基特 
Node.js 微服务工具包
用于微服务的抽象工具包,让节点开发者再次快乐.
安装
$ npm install --save @gatehub/microkit
使用量
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});
追踪
为了能够追踪,它需要包含在开始脚本中,以便在其他一切之前被加载:
"start": "node --require @gatehub/microkit/lib/telemetry.js dist/server.js",
配置
配置参数将从环境变量中获取. 需要以下环境变量:
# 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: 本地配置(所有参数)
从环境中获取的任何配置变量都将优先于配置文件.
示例
{
"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() 可用于将任何对象串入适当的格式.
@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 网络