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

@pluve/logger-sdk

v0.0.4

Published

logger sdk

Readme

@pluve/logger-sdk 使用说明

简介

  • 轻量级前端日志采集 SDK,支持 H5 浏览器环境
  • 使用 Beacon 和像素图(Image)方式上报,确保兼容性与可靠性
  • 标准化日志格式,易于分析和处理

安装与引入

  • 安装:pnpm add @pluve/logger-sdk
  • ESM:import { LoggerSDK } from '@pluve/logger-sdk'
  • UMD:构建后全局为 LoggerSDK

快速开始

import { LoggerSDK } from '@pluve/logger-sdk';

const sdk = new LoggerSDK({
  endpoint: '/api/log',
  appId: 'web-shop',
  env: 'prod', // prod/stage/dev
  debug: true,
});

// 记录错误日志
sdk.track('error', 'TypeError: Cannot read property', {
  level: 'error',
  stack: 'Error stack trace...',
  userId: '123',
  tags: {
    component: 'checkout',
    browser: 'Chrome 120',
  },
});

// 记录带 traceId 的错误(用于关联多个日志)
sdk.track('error', 'Request failed', 'trace-abc-123', {
  level: 'error',
  tags: { api: '/api/user' },
});

// 记录自定义事件
sdk.track('custom', 'User clicked button', {
  level: 'info',
  tags: { action: 'click', button: 'submit' },
});

标准化日志格式

上报的日志数据遵循以下标准格式:

{
  "logId": "550e8400-e29b-41d4-a716-446655440000",  // 日志 ID(UUID v4)
  "traceId": "trace-123456",    // 可选:追踪 ID(用于关联多个日志)
  "eventType": "error",          // 固定:error/crash/pageview/custom
  "ts": 1690000000000,           // 毫秒时间戳
  "appId": "web-shop",           // 应用标识
  "env": "prod",                 // prod/stage/dev
  "level": "error",              // info/warn/error/fatal
  "message": "TypeError: ...",   // 摘要
  "stack": "...",                // 可选:长字符串
  "url": "https://...",          // 发生页面
  "userId": "123",               // 可选:用户ID(脱敏)
  "sessionId": "...",            // 会话标识
  "tags": {                       // 可选的结构化额外信息
    "component": "checkout",
    "browser": "Chrome 120"
  }
}

API

new LoggerSDK(options: SDKOptions)

创建 SDK 实例。

配置项:

interface SDKOptions {
  endpoint: string; // 上报端点 URL(必选)
  appId?: string; // 应用 ID,默认 'unknown'
  env?: Env; // 环境标识:prod/stage/dev,默认 'dev'
  debug?: boolean; // 是否开启调试模式
  pixelParam?: string; // 像素上报参数名,默认 'data'
  maxPixelUrlLen?: number; // 像素上报 URL 最大长度,默认 1900
}

track(eventType, message, traceId?, options?)

记录事件日志。每条日志会自动生成唯一的 logId(UUID v4 格式)。

参数:

  • eventType: 事件类型('error' | 'crash' | 'pageview' | 'custom'
  • message: 摘要信息
  • traceId: (可选) 追踪 ID,用于关联多个相关日志
  • options: 可选配置
    • level?: 日志级别('info' | 'warn' | 'error' | 'fatal'),默认 'info'
    • stack?: 堆栈信息
    • userId?: 用户 ID
    • tags?: 额外的结构化信息

示例:

// 记录错误
sdk.track('error', 'Failed to load resource', {
  level: 'error',
  stack: error.stack,
  userId: '123',
  tags: { resource: 'image.png' },
});

// 记录带 traceId 的错误(用于关联多个日志)
sdk.track('error', 'API request failed', 'trace-xyz-789', {
  level: 'error',
  tags: { endpoint: '/api/users', statusCode: 500 },
});

// 记录页面浏览
sdk.track('pageview', 'User viewed product page', {
  level: 'info',
  tags: { productId: 'P123' },
});

日志 ID 和追踪 ID

  • logId: 每条日志自动生成的唯一标识符(UUID v4 格式),用于全局唯一定位日志
  • traceId: 可选的追踪 ID,用于关联同一请求链路上的多个日志(例如:前端请求、后端处理、数据库查询等)
// 在请求开始时生成 traceId
const traceId = `trace-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;

// 在请求的不同阶段使用相同的 traceId
sdk.track('custom', 'Request started', traceId, {
  level: 'info',
  tags: { endpoint: '/api/checkout' },
});

// ... 请求处理 ...

sdk.track('error', 'Request failed', traceId, {
  level: 'error',
  tags: { endpoint: '/api/checkout', error: 'Network timeout' },
});

identify(userId: string)

设置用户 ID(用于后续日志关联)。

destroy()

销毁 SDK 实例,停止所有监听。

自动采集

SDK 会自动监听以下页面事件并上报:

  • 页面隐藏visibilitychange):当页面变为隐藏状态时
  • 页面卸载pagehide, beforeunload):当用户离开页面时

这些事件使用 Beacon API 上报,确保在页面关闭时仍能成功发送。

上报方式

SDK 使用两种上报方式,按优先级自动选择:

1. Beacon API(优先)

  • 兼容性:Chrome 39+, Firefox 31+, Edge 14+
  • 特点:页面卸载时可靠传输,不阻塞页面关闭
  • 限制:无法获取响应,队列大小限制(通常 64KB)

2. Image 像素上报(降级)

  • 兼容性:所有浏览器
  • 特点:轻量级,无跨域限制
  • 限制:URL 长度限制(默认 1900 字符)

如果 Beacon 失败,会自动降级到 Image 方式。

使用场景

错误监控

// 全局错误捕获
window.addEventListener('error', (event) => {
  sdk.track('error', event.message, {
    level: 'error',
    stack: event.error?.stack,
    tags: {
      filename: event.filename,
      lineno: event.lineno,
      colno: event.colno,
    },
  });
});

// Promise 错误捕获
window.addEventListener('unhandledrejection', (event) => {
  sdk.track('error', 'Unhandled Promise Rejection', {
    level: 'error',
    stack: event.reason?.stack || String(event.reason),
  });
});

页面浏览统计

// 记录页面浏览
sdk.track('pageview', document.title, {
  level: 'info',
  tags: {
    path: window.location.pathname,
    referrer: document.referrer,
  },
});

用户行为追踪

// 记录用户点击
button.addEventListener('click', () => {
  sdk.track('custom', 'Button clicked', {
    level: 'info',
    userId: currentUserId,
    tags: {
      buttonId: button.id,
      page: 'checkout',
    },
  });
});

最佳实践

  1. 设置正确的环境标识:确保在不同环境(prod/stage/dev)使用正确的配置
  2. 使用有意义的 message:摘要信息应简洁明了,便于快速定位问题
  3. 合理使用 tags:将额外的结构化信息放在 tags 中,便于分析和过滤
  4. 用户隐私保护:userId 应该经过脱敏处理
  5. 控制日志量:避免在高频操作中记录过多日志

调试

开启调试模式查看控制台输出:

const sdk = new LoggerSDK({
  endpoint: '/api/log',
  debug: true, // 开启调试
});