阿里云主机折上折
  • 微信号
Current Site:Index > Preliminary setup of performance monitoring tools

Preliminary setup of performance monitoring tools

Author:Chuan Chen 阅读数:8538人阅读 分类: Node.js

Initial Setup of Performance Monitoring Tools

Integrating performance monitoring tools into a Koa2 application helps developers quickly identify performance bottlenecks. Common tools include koa-respond-time, koa-better-http-proxy, etc. The following configuration examples illustrate how to implement basic monitoring functionality.

Response Time Monitoring

Using the koa-response-time middleware automatically adds the X-Response-Time field to response headers:

const Koa = require('koa');
const responseTime = require('koa-response-time');

const app = new Koa();
app.use(responseTime());

app.use(async ctx => {
  ctx.body = 'Hello World';
});

app.listen(3000);

When testing requests, you will see response headers similar to:

X-Response-Time: 12.345ms

Memory Leak Detection

Create memory snapshots using the heapdump module:

const heapdump = require('heapdump');
const fs = require('fs');

setInterval(() => {
  const filename = `${Date.now()}.heapsnapshot`;
  heapdump.writeSnapshot(filename, err => {
    if (err) console.error(err);
    else console.log(`Dumped ${filename}`);
  });
}, 60 * 1000);

Request Latency Analysis

Custom middleware to log slow requests:

app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  
  if (ms > 500) {
    console.warn(`Slow request: ${ctx.method} ${ctx.url} - ${ms}ms`);
  }
  
  ctx.set('X-Response-Time', `${ms}ms`);
});

Error Tracking Integration

Integrate Sentry for exception monitoring:

const Sentry = require('@sentry/node');
const Koa = require('koa');

Sentry.init({ dsn: 'YOUR_DSN_HERE' });

const app = new Koa();

app.on('error', (err, ctx) => {
  Sentry.withScope(scope => {
    scope.addEventProcessor(event => 
      Sentry.Handlers.parseRequest(event, ctx.request)
    );
    Sentry.captureException(err);
  });
});

Database Query Monitoring

Listen to query events in TypeORM:

import { createConnection, Connection } from "typeorm";

createConnection().then(connection => {
  connection.subscribe(event => {
    if (event.query) {
      console.log(`Query: ${event.query}`);
      console.log(`Parameters: ${event.parameters}`);
      console.log(`Duration: ${event.duration}ms`);
    }
  });
});

Process Metrics Collection

Use prom-client to expose Prometheus-format metrics:

const client = require('prom-client');
const collectDefaultMetrics = client.collectDefaultMetrics;

collectDefaultMetrics({ timeout: 5000 });

app.use(async (ctx, next) => {
  if (ctx.path === '/metrics') {
    ctx.set('Content-Type', client.register.contentType);
    ctx.body = client.register.metrics();
    return;
  }
  await next();
});

Distributed Tracing Configuration

Jaeger client initialization example:

const jaeger = require('jaeger-client');

const tracer = jaeger.initTracer({
  serviceName: 'koa-app',
  sampler: {
    type: 'const',
    param: 1,
  },
  reporter: {
    logSpans: true,
    agentHost: 'localhost',
  },
});

app.use(async (ctx, next) => {
  const span = tracer.startSpan(ctx.path);
  await next();
  span.finish();
});

Structured Logging

Use winston to create leveled logs:

const winston = require('winston');

const logger = winston.createLogger({
  level: 'debug',
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

app.use(async (ctx, next) => {
  logger.info(`${ctx.method} ${ctx.url}`);
  await next();
});

Real-Time Performance Dashboard

Install koa-webpack with Webpack Dashboard:

const Dashboard = require('webpack-dashboard');
const DashboardPlugin = require('webpack-dashboard/plugin');

const dashboard = new Dashboard();
compiler.apply(new DashboardPlugin(dashboard.setData));

app.use(require('koa-webpack')({
  compiler,
  devMiddleware: {
    publicPath: '/',
    stats: 'minimal'
  }
}));

Custom Performance Metrics

Example of recording business-specific metrics:

const userTiming = new Map();

app.use(async (ctx, next) => {
  const start = process.hrtime();
  await next();
  const diff = process.hrtime(start);
  const ms = diff[0] * 1e3 + diff[1] * 1e-6;
  
  userTiming.set(ctx.path, (userTiming.get(ctx.path) || 0) + ms);
});

Alert Rule Configuration

Prometheus Alertmanager example rules:

groups:
- name: koa-rules
  rules:
  - alert: HighLatency
    expr: http_request_duration_seconds{quantile="0.95"} > 1
    for: 5m
    labels:
      severity: warning
    annotations:
      summary: "High latency on {{ $labels.instance }}"
      description: "95th percentile latency is {{ $value }}s"

Browser Performance Correlation

Inject Trace ID into the frontend:

app.use(async (ctx, next) => {
  ctx.state.traceId = generateTraceId();
  await next();
  ctx.set('X-Trace-Id', ctx.state.traceId);
});

// Frontend code
fetch('/api/data', {
  headers: {
    'X-Trace-Id': window.performance.now().toString(36)
  }
})

Load Testing Integration

Artillery test script example:

config:
  target: "http://localhost:3000"
  phases:
    - duration: 60
      arrivalRate: 10
scenarios:
  - flow:
      - get:
          url: "/api"
      - think: 1

Container Environment Adaptation

Docker health check configuration:

HEALTHCHECK --interval=30s --timeout=3s \
  CMD curl -f http://localhost:3000/health || exit 1

Corresponding Koa route implementation:

router.get('/health', ctx => {
  ctx.body = { 
    status: 'UP',
    db: checkDatabase(),
    memory: process.memoryUsage()
  };
});

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.