监控与分析 #

监控概述 #

Vercel 提供全面的监控和分析功能:

text
┌─────────────────────────────────────────┐
│        Vercel 监控功能                   │
├─────────────────────────────────────────┤
│  Analytics    →  访问统计与性能分析     │
│  Web Vitals   →  核心性能指标           │
│  Logs         →  实时日志               │
│  Speed Insights →  性能洞察             │
└─────────────────────────────────────────┘

Vercel Analytics #

启用 Analytics #

text
Project Settings → Analytics → Enable
text
┌─────────────────────────────────────────┐
│  Enable Analytics                       │
├─────────────────────────────────────────┤
│  ☑ Enable Web Analytics                 │
│  ☑ Enable Web Vitals                    │
│                                         │
│  [Enable]                               │
└─────────────────────────────────────────┘

安装 Analytics 包 #

bash
npm install @vercel/analytics

Next.js 集成 #

App Router:

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

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>
        {children}
        <Analytics />
      </body>
    </html>
  )
}

Pages Router:

tsx
import { Analytics } from '@vercel/analytics/react'
import type { AppProps } from 'next/app'

export default function App({ Component, pageProps }: AppProps) {
  return (
    <>
      <Component {...pageProps} />
      <Analytics />
    </>
  )
}

查看分析数据 #

text
Project → Analytics
├── Visitors
├── Page Views
├── Top Pages
├── Countries
├── Devices
├── Browsers
└── Web Vitals

访问统计 #

访客数据 #

text
┌─────────────────────────────────────────┐
│  Visitors                               │
├─────────────────────────────────────────┤
│  Today:        1,234                    │
│  This Week:    8,567                    │
│  This Month:   32,456                   │
│                                         │
│  [View Details]                         │
└─────────────────────────────────────────┘

页面浏览量 #

text
┌─────────────────────────────────────────┐
│  Page Views                             │
├─────────────────────────────────────────┤
│  /              12,345 views            │
│  /blog          8,234 views             │
│  /about         3,456 views             │
│  /contact       1,234 views             │
└─────────────────────────────────────────┘

地理分布 #

text
┌─────────────────────────────────────────┐
│  Top Countries                          │
├─────────────────────────────────────────┤
│  🇺🇸 United States    35%               │
│  🇬🇧 United Kingdom   15%               │
│  🇩🇪 Germany          12%               │
│  🇫🇷 France           8%                │
│  🇯🇵 Japan            6%                │
└─────────────────────────────────────────┘

设备与浏览器 #

text
┌─────────────────────────────────────────┐
│  Devices                                │
├─────────────────────────────────────────┤
│  Desktop    55%                         │
│  Mobile     40%                         │
│  Tablet     5%                          │
└─────────────────────────────────────────┘

┌─────────────────────────────────────────┐
│  Browsers                               │
├─────────────────────────────────────────┤
│  Chrome     65%                         │
│  Safari     20%                         │
│  Firefox    10%                         │
│  Edge       5%                          │
└─────────────────────────────────────────┘

Web Vitals #

核心指标 #

指标 全称 说明 良好值
LCP Largest Contentful Paint 最大内容绘制 < 2.5s
FID First Input Delay 首次输入延迟 < 100ms
CLS Cumulative Layout Shift 累积布局偏移 < 0.1
TTFB Time to First Byte 首字节时间 < 600ms
INP Interaction to Next Paint 交互到下次绘制 < 200ms

查看 Web Vitals #

text
Project → Analytics → Web Vitals
text
┌─────────────────────────────────────────┐
│  Web Vitals                             │
├─────────────────────────────────────────┤
│  LCP:  1.8s  ████████░░  Good           │
│  FID:  45ms  ██████████  Good           │
│  CLS:  0.05  ██████████  Good           │
│  TTFB: 0.3s  ██████████  Good           │
│  INP:  120ms ████████░░  Needs Work     │
└─────────────────────────────────────────┘

自定义 Web Vitals #

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

export function WebVitals() {
  useReportWebVitals((metric) => {
    console.log(metric)
  })
}

发送到分析服务 #

typescript
import { useReportWebVitals } from 'next/web-vitals'
import { sendToAnalytics } from '@/lib/analytics'

export function WebVitals() {
  useReportWebVitals((metric) => {
    sendToAnalytics({
      name: metric.name,
      value: metric.value,
      id: metric.id,
    })
  })
}

Speed Insights #

启用 Speed Insights #

bash
npm install @vercel/speed-insights

Next.js 集成 #

tsx
import { SpeedInsights } from '@vercel/speed-insights/next'
import { Analytics } from '@vercel/analytics/react'

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>
        {children}
        <SpeedInsights />
        <Analytics />
      </body>
    </html>
  )
}

查看 Speed Insights #

text
Project → Speed Insights
├── Performance Score
├── LCP Analysis
├── TTFB Analysis
└── Recommendations

日志功能 #

查看实时日志 #

text
Project → Deployments → [Deployment] → Logs
text
┌─────────────────────────────────────────┐
│  Function Logs                          │
├─────────────────────────────────────────┤
│  [10:30:00] Request received            │
│  [10:30:00] Processing data...          │
│  [10:30:01] Response sent               │
│                                         │
│  [10:30:15] Request received            │
│  [10:30:15] Error: Invalid input        │
└─────────────────────────────────────────┘

CLI 查看日志 #

bash
vercel logs [deployment-url]

实时日志流 #

bash
vercel logs --follow

日志过滤 #

bash
vercel logs --filter "error"
vercel logs --filter "api"

自定义日志 #

结构化日志 #

typescript
export async function GET() {
  console.log(JSON.stringify({
    level: 'info',
    message: 'API request received',
    timestamp: new Date().toISOString(),
    requestId: crypto.randomUUID(),
    path: '/api/users',
  }))
  
  return Response.json({ status: 'ok' })
}

错误日志 #

typescript
export async function GET() {
  try {
    const data = await fetchData()
    return Response.json(data)
  } catch (error) {
    console.error(JSON.stringify({
      level: 'error',
      message: error.message,
      stack: error.stack,
      timestamp: new Date().toISOString(),
    }))
    
    return Response.json({ error: 'Internal Server Error' }, { status: 500 })
  }
}

监控告警 #

配置告警 #

text
Project Settings → Notifications
text
┌─────────────────────────────────────────┐
│  Notification Settings                  │
├─────────────────────────────────────────┤
│  ☑ Deployment Failed                    │
│  ☑ Deployment Succeeded                 │
│  ☐ High Error Rate                      │
│  ☐ Performance Degradation              │
│                                         │
│  Notification Channels:                 │
│  ☑ Email                                │
│  ☑ Slack                                │
│  ☐ PagerDuty                            │
└─────────────────────────────────────────┘

Slack 集成 #

text
Project Settings → Git → Notifications → Slack
text
1. 点击 "Add Slack Integration"
2. 选择 Slack 工作区
3. 选择通知频道
4. 配置通知事件

Webhook 告警 #

typescript
export async function POST(request: Request) {
  const event = await request.json()
  
  if (event.type === 'deployment.failed') {
    await sendAlert({
      message: `Deployment failed: ${event.payload.url}`,
      severity: 'high',
    })
  }
  
  return Response.json({ received: true })
}

性能监控 #

实时用户监控 (RUM) #

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

export default function Layout({ children }) {
  return (
    <>
      {children}
      <Analytics mode="production" />
    </>
  )
}

合成监控 #

text
Project → Speed Insights → Run Test

性能预算 #

json
{
  "budgets": [
    {
      "resourceType": "script",
      "budget": 300
    },
    {
      "resourceType": "total",
      "budget": 1000
    }
  ]
}

数据导出 #

导出分析数据 #

text
Project → Analytics → Export

API 获取数据 #

bash
curl "https://api.vercel.com/v1/analytics/$PROJECT_ID" \
  -H "Authorization: Bearer $VERCEL_TOKEN"

最佳实践 #

监控清单 #

text
┌─────────────────────────────────────────┐
│        监控最佳实践                      │
├─────────────────────────────────────────┤
│  ✓ 启用 Analytics                       │
│  ✓ 监控 Web Vitals                      │
│  ✓ 设置性能预算                         │
│  ✓ 配置告警通知                         │
│  ✓ 定期审查日志                         │
│  ✓ 分析用户行为                         │
│  ✓ 优化慢速页面                         │
└─────────────────────────────────────────┘

性能优化建议 #

text
LCP 优化:
├── 优化服务器响应时间
├── 使用 CDN
├── 预加载关键资源
└── 优化图片

FID/INP 优化:
├── 减少 JavaScript 执行时间
├── 分割长任务
└── 使用 Web Worker

CLS 优化:
├── 设置图片尺寸
├── 预留广告位空间
└── 避免动态插入内容

下一步 #

了解监控与分析后,接下来学习 性能优化 深入了解性能优化技巧!

最后更新:2026-03-28