import { register, collectDefaultMetrics } from 'prom-client';
// Create a custom counter metric for counting HTTP requests
const httpRequestCount = new Counter({
name: 'http_requests_total',
help: 'Total number of HTTP requests',
labelNames: ['method', 'route', 'statusCode'],
});
// Initialize Prometheus metrics collection
collectDefaultMetrics();
// Export a middleware function to expose a /metrics endpoint
export default function (req, res) {
res.set('Content-Type', register.contentType);
res.end(register.metrics());
}
// Export the custom counter metric for use in your application
export { httpRequestCount };
然后导入httpRequestCount:
import { httpRequestCount } from './prometheus';
export default function handler(req, res) {
// Increment the httpRequestCount metric for this request
httpRequestCount.inc({
method: req.method,
route: req.url,
statusCode: res.statusCode,
});
// Handle the request and send the response
// ...
1条答案
按热度按时间fae0ux8s1#
你可以尝试安装npm包:
然后,您可以尝试在Next.js pages目录中创建一个名为
prometheus.js
的新文件:然后导入httpRequestCount:
在next.config.js文件中为/metrics端点添加路由:
那你就完了!
您可以启动Next.js应用程序并导航到
http://localhost:3000/metrics
以查看Prometheus指标。