Skip to content

Next.js 监控和分析 📊

🎯 概述

监控和分析帮助你了解应用性能、用户行为和潜在问题。

📦 Vercel Analytics

安装

bash
npm install @vercel/analytics

使用

tsx
// app/layout.tsx
import { Analytics } from '@vercel/analytics/react'

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        {children}
        <Analytics />
      </body>
    </html>
  )
}

🚀 Web Vitals

监控核心指标

tsx
// app/web-vitals.tsx
'use client'

import { useReportWebVitals } from 'next/web-vitals'

export function WebVitals() {
  useReportWebVitals((metric) => {
    console.log(metric)
    
    // 发送到分析服务
    fetch('/api/analytics', {
      method: 'POST',
      body: JSON.stringify(metric),
    })
  })
}

指标说明

  • CLS: 累积布局偏移
  • FID: 首次输入延迟
  • FCP: 首次内容绘制
  • LCP: 最大内容绘制
  • TTFB: 首字节时间

📝 错误监控

Sentry 集成

bash
npm install @sentry/nextjs
js
// sentry.client.config.js
import * as Sentry from '@sentry/nextjs'

Sentry.init({
  dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
  tracesSampleRate: 1.0,
})

// sentry.server.config.js
import * as Sentry from '@sentry/nextjs'

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  tracesSampleRate: 1.0,
})

🎨 自定义日志

日志服务

ts
// lib/logger.ts
export function log(level: 'info' | 'warn' | 'error', message: string, data?: any) {
  const logData = {
    level,
    message,
    data,
    timestamp: new Date().toISOString(),
  }
  
  if (process.env.NODE_ENV === 'production') {
    // 发送到日志服务
    fetch('/api/logs', {
      method: 'POST',
      body: JSON.stringify(logData),
    })
  } else {
    console[level](message, data)
  }
}

📊 性能监控

自定义指标

tsx
'use client'

import { useEffect } from 'react'

export function PerformanceMonitor() {
  useEffect(() => {
    // 监控 API 请求时间
    const observer = new PerformanceObserver((list) => {
      for (const entry of list.getEntries()) {
        if (entry.entryType === 'resource') {
          console.log(`${entry.name}: ${entry.duration}ms`)
        }
      }
    })
    
    observer.observe({ entryTypes: ['resource'] })
    
    return () => observer.disconnect()
  }, [])
  
  return null
}

📚 最佳实践

1. 设置告警

ts
// lib/alert.ts
export function sendAlert(message: string, severity: 'low' | 'high') {
  if (severity === 'high') {
    // 发送紧急通知
    fetch('/api/alerts', {
      method: 'POST',
      body: JSON.stringify({ message, severity }),
    })
  }
}

2. 定期审查

  • 每周查看性能指标
  • 监控错误率趋势
  • 分析用户行为

3. 优化响应

  • 设置性能预算
  • 自动化性能测试
  • 持续优化

🔗 相关资源


下一步:学习 Next.js 配置优化