npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@loongsuite/cms_metrics

v1.0.0

Published

## 简介

Readme

@loongsuite/cms_metrics

简介

CMS Metrics 是 CMS 可观测性 SDK 的指标能力包。目前提供基础的指标功能探测,为未来的指标采集与导出实现预留接口。这是可观测性三大支柱(追踪、指标、日志)中指标部分的实现基础。

特性

  • 📊 指标基础: 提供指标功能的基础接口
  • 🔍 可用性探测: 检测指标功能是否可用
  • 🚀 未来扩展: 为完整的指标管线实现预留接口
  • 🔧 类型安全: 完整的 TypeScript 类型支持
  • 📈 标准化: 遵循 OpenTelemetry 指标规范

安装

# 使用 anpm (推荐)
anpm add @loongsuite/cms_metrics

# 或使用 npm
npm install @loongsuite/cms_metrics

当前功能

基础探测

目前主要提供指标功能的可用性检测:

import { info } from '@loongsuite/cms_metrics';

// 检测指标功能是否可用
const status = info();
console.log(status); // 输出: 'cms_metrics ready'

主要导出

import {
  info,
  // 未来可能添加的导出
  Meter,
  Counter,
  Histogram,
  Gauge,
  MetricExporter
} from '@loongsuite/cms_metrics';

使用示例

基础用法

import { info } from '@loongsuite/cms_metrics';

// 检查指标功能状态
const metricsStatus = info();
console.log('Metrics functionality status:', metricsStatus);

// 在应用启动时检查
if (metricsStatus === 'cms_metrics ready') {
  console.log('Metrics system is ready');
} else {
  console.warn('Metrics system is not available');
}

与 NodeSDK 集成

import { NodeSDK } from '@loongsuite/cms_node_sdk';
import { info } from '@loongsuite/cms_metrics';

const sdk = new NodeSDK({
  serviceName: 'my-service'
});

// 启动前检查指标功能
const metricsStatus = info();
console.log('Metrics status before SDK start:', metricsStatus);

sdk.start();

// 启动后再次检查
const postStartStatus = info();
console.log('Metrics status after SDK start:', postStartStatus);

条件性指标处理

import { info } from '@loongsuite/cms_metrics';

class ApplicationMetrics {
  private isMetricsAvailable: boolean;

  constructor() {
    this.isMetricsAvailable = info() === 'cms_metrics ready';
  }

  recordCounter(name: string, value: number, labels?: Record<string, string>) {
    if (this.isMetricsAvailable) {
      // 使用 CMS 指标系统
      this.recordWithCMS(name, value, labels);
    } else {
      // 降级到简单计数
      console.log(`[METRIC] ${name}: ${value}`, labels);
    }
  }

  recordHistogram(name: string, value: number, labels?: Record<string, string>) {
    if (this.isMetricsAvailable) {
      // 使用 CMS 指标系统
      this.recordHistogramWithCMS(name, value, labels);
    } else {
      // 降级处理
      console.log(`[HISTOGRAM] ${name}: ${value}`, labels);
    }
  }

  private recordWithCMS(name: string, value: number, labels?: Record<string, string>) {
    // 未来实现 CMS 指标记录
    console.log(`[CMS-METRIC] ${name}: ${value}`, labels);
  }

  private recordHistogramWithCMS(name: string, value: number, labels?: Record<string, string>) {
    // 未来实现 CMS 直方图记录
    console.log(`[CMS-HISTOGRAM] ${name}: ${value}`, labels);
  }
}

// 使用示例
const metrics = new ApplicationMetrics();

// 记录请求计数
metrics.recordCounter('http_requests_total', 1, {
  method: 'GET',
  status: '200',
  endpoint: '/api/users'
});

// 记录响应时间
metrics.recordHistogram('http_request_duration_ms', 150, {
  method: 'GET',
  endpoint: '/api/users'
});

未来规划

计划中的功能

  1. Meter 接口: 提供指标记录器接口
  2. Counter: 计数器指标类型
  3. Histogram: 直方图指标类型
  4. Gauge: 仪表盘指标类型
  5. MetricExporter: 指标导出器(Prometheus、OTLP 等)
  6. 自动关联: 与追踪数据的自动关联

预期 API 设计

// 未来可能的 API 设计
import { 
  Meter, 
  Counter, 
  Histogram, 
  Gauge,
  BatchMetricProcessor,
  PrometheusExporter 
} from '@loongsuite/cms_metrics';

// 创建指标记录器
const meter = new Meter('my-service', '1.0.0');

// 创建计数器
const requestCounter = meter.createCounter('http_requests_total', {
  description: 'Total number of HTTP requests',
  unit: '1'
});

// 创建直方图
const requestDuration = meter.createHistogram('http_request_duration_ms', {
  description: 'HTTP request duration in milliseconds',
  unit: 'ms',
  buckets: [10, 50, 100, 500, 1000, 5000]
});

// 创建仪表盘
const activeConnections = meter.createGauge('active_connections', {
  description: 'Number of active connections',
  unit: '1'
});

// 记录指标
requestCounter.add(1, { method: 'GET', status: '200' });
requestDuration.record(150, { method: 'GET', endpoint: '/api/users' });
activeConnections.set(42);

// 配置指标处理器
const metricProcessor = new BatchMetricProcessor(
  new PrometheusExporter({ port: 9090 }),
  { scheduledDelayMillis: 5000 }
);

与追踪集成

当前集成方式

import { info } from '@loongsuite/cms_metrics';
import { NodeSDK } from '@loongsuite/cms_node_sdk';

const sdk = new NodeSDK({
  serviceName: 'my-service'
});

sdk.start();

// 在追踪上下文中记录指标状态
const tracer = sdk.getTracerManager().getTracer('my-service');
const span = tracer.startSpan('metrics-check');

span.setAttributes({
  'metrics.status': info(),
  'metrics.available': info() === 'cms_metrics ready'
});

span.end();

未来集成规划

// 未来可能的集成方式
import { Meter } from '@loongsuite/cms_metrics';
import { NodeSDK } from '@loongsuite/cms_node_sdk';

const sdk = new NodeSDK({
  serviceName: 'my-service'
});

sdk.start();

// 自动关联追踪上下文
const meter = new Meter('my-service', '1.0.0');
const requestCounter = meter.createCounter('http_requests_total');

// 指标会自动包含当前 span 信息
requestCounter.add(1, {
  method: 'GET',
  status: '200',
  trace_id: 'abc123...' // 自动关联
});

指标类型

未来支持的指标类型

  1. Counter: 单调递增的计数器
  2. Histogram: 分布统计的直方图
  3. Gauge: 可增减的仪表盘
  4. Summary: 分位数统计摘要

使用场景

// Counter - 请求计数
const requestCounter = meter.createCounter('http_requests_total');
requestCounter.add(1, { method: 'GET', status: '200' });

// Histogram - 响应时间分布
const responseTime = meter.createHistogram('http_response_time_ms');
responseTime.record(150, { endpoint: '/api/users' });

// Gauge - 当前连接数
const connections = meter.createGauge('active_connections');
connections.set(42);

// Summary - 分位数统计
const latency = meter.createSummary('request_latency_ms');
latency.record(100, { service: 'user-service' });

最佳实践

当前最佳实践

  1. 启动时检查: 在应用启动时检查指标功能可用性
  2. 降级处理: 提供指标功能不可用时的降级方案
  3. 状态监控: 定期检查指标功能状态
import { info } from '@loongsuite/cms_metrics';

class MetricsMonitor {
  private checkInterval: NodeJS.Timeout;

  start() {
    // 定期检查指标功能状态
    this.checkInterval = setInterval(() => {
      const status = info();
      if (status !== 'cms_metrics ready') {
        console.warn('Metrics system status changed:', status);
      }
    }, 30000); // 每30秒检查一次
  }

  stop() {
    if (this.checkInterval) {
      clearInterval(this.checkInterval);
    }
  }
}

未来最佳实践

  1. 指标命名: 使用清晰的指标命名规范
  2. 标签设计: 合理设计标签维度
  3. 性能考虑: 避免在高频路径中记录过多指标
// 好的指标命名
const goodMetrics = {
  'http_requests_total': 'HTTP请求总数',
  'http_request_duration_ms': 'HTTP请求耗时',
  'database_connections_active': '活跃数据库连接数'
};

// 避免的指标命名
const badMetrics = {
  'requests': '太模糊',
  'time': '不明确',
  'connections': '缺少上下文'
};

故障排除

常见问题

  1. 功能不可用: 检查是否正确安装和导入
  2. 状态异常: 检查 NodeSDK 是否正确启动

调试技巧

import { info } from '@loongsuite/cms_metrics';

// 详细的状态检查
function checkMetricsStatus() {
  const status = info();
  console.log('Metrics status check:', {
    status,
    timestamp: new Date().toISOString(),
    nodeVersion: process.version,
    environment: process.env.NODE_ENV
  });
  
  return status === 'cms_metrics ready';
}

// 在关键点检查状态
checkMetricsStatus();

依赖

  • @loongsuite/cms_core: 核心类型和接口定义(未来可能)

许可证

MIT License