LogRocket 高级功能 #
概述 #
本章介绍 LogRocket 的高级功能,帮助你更深入地利用 LogRocket 进行前端监控和分析。
text
┌─────────────────────────────────────────────────────────────┐
│ 高级功能概览 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 集成扩展: │
│ ├── 第三方工具集成 │
│ ├── 自定义数据上报 │
│ └── Webhook 配置 │
│ │
│ API 功能: │
│ ├── REST API │
│ ├── GraphQL API │
│ └── SDK 扩展 │
│ │
│ 数据分析: │
│ ├── 自定义仪表板 │
│ ├── 数据导出 │
│ └── 高级搜索 │
│ │
│ 团队协作: │
│ ├── 权限管理 │
│ ├── 工作流集成 │
│ └── 通知配置 │
│ │
└─────────────────────────────────────────────────────────────┘
第三方集成 #
Slack 集成 #
text
┌─────────────────────────────────────────────────────────────┐
│ Slack 集成 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 配置步骤: │
│ │
│ 1. 在 LogRocket 控制台进入 Settings > Integrations │
│ 2. 选择 Slack 并点击 Connect │
│ 3. 授权 LogRocket 访问 Slack 工作区 │
│ 4. 选择要发送通知的频道 │
│ 5. 配置通知规则 │
│ │
│ 通知类型: │
│ - 新错误告警 │
│ - 性能问题告警 │
│ - 自定义事件通知 │
│ │
│ 消息格式: │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ 🚨 New Error in Production │ │
│ │ │ │
│ │ TypeError: Cannot read property 'id' │ │
│ │ Users affected: 15 │ │
│ │ First seen: 5 minutes ago │ │
│ │ │ │
│ │ [View Session] [View Error] │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
Jira 集成 #
javascript
// 在 LogRocket 中配置 Jira 集成
// Settings > Integrations > Jira
// 功能:
// 1. 从错误创建 Jira 工单
// 2. 自动附加会话链接
// 3. 同步错误状态
// 创建工单时包含的信息:
{
"summary": "TypeError: Cannot read property 'id'",
"description": `
Error Details:
- Type: TypeError
- Message: Cannot read property 'id' of undefined
- URL: /dashboard
- Browser: Chrome 120.0
Session Recording: ${LogRocket.sessionURL}
Stack Trace:
${error.stack}
`,
"priority": "High",
"labels": ["frontend", "bug"]
}
PagerDuty 集成 #
text
┌─────────────────────────────────────────────────────────────┐
│ PagerDuty 集成 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 配置步骤: │
│ 1. 在 PagerDuty 创建新服务 │
│ 2. 获取 Integration Key │
│ 3. 在 LogRocket 配置 PagerDuty 集成 │
│ 4. 配置告警规则 │
│ │
│ 使用场景: │
│ - 关键错误需要立即响应 │
│ - 严重性能问题 │
│ - 服务可用性问题 │
│ │
│ 告警级别: │
│ - Critical: 立即通知 │
│ - Warning: 批量通知 │
│ - Info: 仅记录 │
│ │
└─────────────────────────────────────────────────────────────┘
Zendesk 集成 #
javascript
// Zendesk 工单自动附加 LogRocket 会话
// 配置后,客服可以:
// 1. 查看用户最近的会话
// 2. 直接跳转到问题发生时刻
// 3. 分享会话给开发团队
// 在工单中显示:
// - 用户 ID
// - 最近会话链接
// - 错误摘要
// - 性能指标
Webhook 配置 #
配置 Webhook #
javascript
// 在 LogRocket 控制台配置 Webhook
// Settings > Integrations > Webhooks
// Webhook URL
const webhookUrl = 'https://your-server.com/logrocket-webhook';
// 触发事件
const events = [
'error.created',
'error.resolved',
'session.created',
'performance.threshold_exceeded'
];
Webhook 载荷格式 #
javascript
// 错误事件载荷
{
"event": "error.created",
"timestamp": "2024-01-20T10:30:00Z",
"data": {
"error": {
"id": "err_123",
"type": "TypeError",
"message": "Cannot read property 'id' of undefined",
"url": "https://example.com/dashboard",
"stacktrace": [...]
},
"session": {
"id": "sess_456",
"url": "https://app.logrocket.com/..."
},
"user": {
"id": "user_789",
"email": "john@example.com"
},
"environment": {
"browser": "Chrome 120.0",
"os": "Windows 10"
}
}
}
// 性能事件载荷
{
"event": "performance.threshold_exceeded",
"timestamp": "2024-01-20T10:30:00Z",
"data": {
"metric": "LCP",
"value": 4500,
"threshold": 2500,
"url": "https://example.com/products",
"session": {
"id": "sess_456",
"url": "https://app.logrocket.com/..."
}
}
}
Webhook 处理示例 #
javascript
// Node.js Express 示例
const express = require('express');
const crypto = require('crypto');
const app = express();
app.post('/logrocket-webhook', express.json(), (req, res) => {
const signature = req.headers['x-logrocket-signature'];
const payload = JSON.stringify(req.body);
// 验证签名
const expectedSignature = crypto
.createHmac('sha256', process.env.LOGROCKET_WEBHOOK_SECRET)
.update(payload)
.digest('hex');
if (signature !== expectedSignature) {
return res.status(401).send('Invalid signature');
}
const { event, data } = req.body;
switch (event) {
case 'error.created':
handleNewError(data);
break;
case 'performance.threshold_exceeded':
handlePerformanceIssue(data);
break;
default:
console.log('Unknown event:', event);
}
res.status(200).send('OK');
});
function handleNewError(data) {
// 发送到内部错误追踪系统
// 通知相关团队
// 创建工单
}
function handlePerformanceIssue(data) {
// 记录性能问题
// 分析趋势
}
REST API #
API 认证 #
bash
# 获取 API Key
# Settings > API Keys > Create API Key
# 使用 API Key
curl -H "Authorization: Bearer YOUR_API_KEY" \
https://api.logrocket.com/v1/apps/your-app-id/sessions
常用 API 端点 #
text
┌─────────────────────────────────────────────────────────────┐
│ REST API 端点 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 会话相关: │
│ GET /v1/apps/:appId/sessions 获取会话列表 │
│ GET /v1/apps/:appId/sessions/:id 获取会话详情 │
│ GET /v1/apps/:appId/sessions/:id/url 获取会话 URL │
│ │
│ 错误相关: │
│ GET /v1/apps/:appId/errors 获取错误列表 │
│ GET /v1/apps/:appId/errors/:id 获取错误详情 │
│ POST /v1/apps/:appId/errors/:id/resolve 解决错误 │
│ │
│ 用户相关: │
│ GET /v1/apps/:appId/users 获取用户列表 │
│ GET /v1/apps/:appId/users/:id 获取用户详情 │
│ │
│ 性能相关: │
│ GET /v1/apps/:appId/performance 获取性能指标 │
│ GET /v1/apps/:appId/performance/pages 获取页面性能 │
│ │
└─────────────────────────────────────────────────────────────┘
API 使用示例 #
javascript
// 获取最近的错误列表
async function getRecentErrors(appId, apiKey) {
const response = await fetch(
`https://api.logrocket.com/v1/apps/${appId}/errors?limit=10`,
{
headers: {
'Authorization': `Bearer ${apiKey}`
}
}
);
return response.json();
}
// 获取用户会话
async function getUserSessions(appId, apiKey, userId) {
const response = await fetch(
`https://api.logrocket.com/v1/apps/${appId}/sessions?userId=${userId}`,
{
headers: {
'Authorization': `Bearer ${apiKey}`
}
}
);
return response.json();
}
// 获取性能指标
async function getPerformanceMetrics(appId, apiKey) {
const response = await fetch(
`https://api.logrocket.com/v1/apps/${appId}/performance`,
{
headers: {
'Authorization': `Bearer ${apiKey}`
}
}
);
return response.json();
}
自定义仪表板 #
创建仪表板 #
text
┌─────────────────────────────────────────────────────────────┐
│ 自定义仪表板 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 功能: │
│ - 自定义布局和组件 │
│ - 选择显示的指标 │
│ - 设置时间范围 │
│ - 添加过滤条件 │
│ │
│ 可用组件: │
│ - Core Web Vitals 概览 │
│ - 错误趋势图 │
│ - 用户活跃度 │
│ - 页面性能排名 │
│ - 错误分布 │
│ - 自定义图表 │
│ │
└─────────────────────────────────────────────────────────────┘
仪表板配置示例 #
javascript
// 仪表板配置
const dashboardConfig = {
name: 'E-commerce Dashboard',
timeRange: '7d',
filters: {
environment: 'production',
userSegment: 'premium'
},
widgets: [
{
type: 'metric',
title: 'Total Sessions',
metric: 'sessions.count',
comparison: 'previous_period'
},
{
type: 'chart',
title: 'Error Rate',
chartType: 'line',
metric: 'errors.rate',
granularity: 'day'
},
{
type: 'table',
title: 'Top Errors',
metric: 'errors.top',
limit: 10
},
{
type: 'chart',
title: 'LCP Distribution',
chartType: 'histogram',
metric: 'performance.lcp'
}
]
};
数据导出 #
导出选项 #
text
┌─────────────────────────────────────────────────────────────┐
│ 数据导出 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 导出格式: │
│ - CSV │
│ - JSON │
│ - Excel │
│ │
│ 导出内容: │
│ - 会话数据 │
│ - 错误报告 │
│ - 性能指标 │
│ - 用户数据 │
│ │
│ 导出方式: │
│ - 控制台手动导出 │
│ - API 导出 │
│ - 定期邮件报告 │
│ │
└─────────────────────────────────────────────────────────────┘
API 导出示例 #
javascript
// 导出错误报告
async function exportErrorReport(appId, apiKey, startDate, endDate) {
const response = await fetch(
`https://api.logrocket.com/v1/apps/${appId}/exports/errors`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
startDate: startDate,
endDate: endDate,
format: 'csv'
})
}
);
return response.json();
}
高级搜索 #
搜索语法 #
text
┌─────────────────────────────────────────────────────────────┐
│ 搜索语法 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 基本搜索: │
│ error.message:"Cannot read property" │
│ url:"/checkout" │
│ user.email:"john@example.com" │
│ │
│ 组合搜索: │
│ error.message:"TypeError" AND url:"/dashboard" │
│ error.type:"TypeError" OR error.type:"ReferenceError" │
│ │
│ 排除搜索: │
│ NOT user.email:"test@example.com" │
│ error.message:"TypeError" NOT url:"/test" │
│ │
│ 范围搜索: │
│ performance.lcp:>3000 │
│ session.duration:>300 │
│ │
│ 通配符: │
│ error.message:"Cannot*" │
│ url:"/api/*" │
│ │
└─────────────────────────────────────────────────────────────┘
搜索示例 #
javascript
// 搜索特定用户的错误会话
const searchQuery = `
user.id:"user-123"
AND error.type:"TypeError"
AND timestamp:[2024-01-01 TO 2024-01-31]
`;
// 搜索性能问题
const performanceQuery = `
performance.lcp:>4000
AND url:"/products/*"
AND browser.name:"Safari"
`;
// 搜索特定功能的错误
const featureQuery = `
tag:"feature:checkout"
AND error.level:"error"
`;
团队协作 #
权限管理 #
text
┌─────────────────────────────────────────────────────────────┐
│ 权限管理 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 角色类型: │
│ │
│ Admin(管理员) │
│ - 完全访问权限 │
│ - 管理团队成员 │
│ - 配置集成 │
│ │
│ Developer(开发者) │
│ - 查看所有数据 │
│ - 创建和编辑仪表板 │
│ - 解决错误 │
│ │
│ Viewer(查看者) │
│ - 只读访问 │
│ - 查看仪表板 │
│ - 查看会话 │
│ │
│ 配置方式: │
│ Settings > Team > Invite Members │
│ │
└─────────────────────────────────────────────────────────────┘
工作流集成 #
javascript
// 与 GitHub 集成
// 在 PR 中自动关联相关错误
// 与 CI/CD 集成
// 在部署时检查是否有新错误
// 示例:部署后检查
async function checkForNewErrorsAfterDeploy(appId, apiKey, version) {
const response = await fetch(
`https://api.logrocket.com/v1/apps/${appId}/errors?release=${version}`,
{
headers: {
'Authorization': `Bearer ${apiKey}`
}
}
);
const errors = await response.json();
if (errors.count > 0) {
// 发送告警
// 考虑回滚
console.log(`Found ${errors.count} new errors in version ${version}`);
}
}
自定义插件 #
创建自定义插件 #
javascript
// LogRocket 插件结构
const customPlugin = {
name: 'custom-analytics',
init: function(LogRocket, options) {
this.LogRocket = LogRocket;
this.options = options;
// 监听事件
this.setupEventListeners();
},
setupEventListeners: function() {
// 监听错误
window.addEventListener('error', this.handleError.bind(this));
// 监听性能
if (window.performance) {
this.trackPerformance();
}
},
handleError: function(event) {
// 自定义错误处理
this.LogRocket.captureException(event.error, {
tags: {
plugin: this.name
}
});
},
trackPerformance: function() {
// 自定义性能追踪
const timing = window.performance.timing;
const metrics = {
domContentLoaded: timing.domContentLoadedEventEnd - timing.navigationStart,
load: timing.loadEventEnd - timing.navigationStart
};
this.LogRocket.track('Performance Metrics', metrics);
}
};
// 注册插件
LogRocket.registerPlugin(customPlugin, {
// 插件配置
});
插件 API #
javascript
// 插件可用的 LogRocket API
const pluginAPI = {
// 日志
log: LogRocket.log,
info: LogRocket.info,
warn: LogRocket.warn,
error: LogRocket.error,
// 事件
track: LogRocket.track,
addBreadcrumb: LogRocket.addBreadcrumb,
// 错误
captureException: LogRocket.captureException,
// 用户
identify: LogRocket.identify,
// 标签
setTag: LogRocket.setTag
};
高级配置 #
采样率配置 #
javascript
LogRocket.init('your-app-id/app-name', {
// 会话采样率
sessionSamplingRate: 0.1, // 10% 的会话
// 错误采样率
errorSamplingRate: 1.0, // 100% 的错误
// 性能采样率
performanceSamplingRate: 0.5, // 50% 的性能数据
// 网络请求采样
networkSamplingRate: 0.3 // 30% 的网络请求
});
自定义上报端点 #
javascript
LogRocket.init('your-app-id/app-name', {
// 自定义上报端点(企业版功能)
ingestEndpoint: 'https://ingest.your-domain.com',
// 代理配置
proxy: {
ingest: '/api/logrocket/ingest',
sessions: '/api/logrocket/sessions'
}
});
离线支持 #
javascript
LogRocket.init('your-app-id/app-name', {
// 离线缓存配置
offline: {
enabled: true,
maxQueueSize: 100, // 最大缓存事件数
maxRetryAttempts: 3 // 最大重试次数
}
});
下一步 #
现在你已经掌握了 LogRocket 的高级功能,接下来学习 最佳实践 了解如何在生产环境中高效使用 LogRocket!
最后更新:2026-03-29