分析用户行为是优化产品体验、改进业务决策的重要手段。下面介绍如何在 Node.js 环境中收集和分析用户行为日志。
const express = require('express');
const morgan = require('morgan');
const fs = require('fs');
const path = require('path');
const app = express();
// 创建访问日志写入流
const accessLogStream = fs.createWriteStream(
path.join(__dirname, 'access.log'),
{ flags: 'a' }
);
// 使用morgan记录HTTP访问日志
app.use(morgan('combined', { stream: accessLogStream }));
// 自定义用户行为日志中间件
app.use((req, res, next) => {
const userAction = {
timestamp: new Date().toISOString(),
userId: req.user?.id || 'anonymous',
path: req.path,
method: req.method,
query: req.query,
params: req.params,
userAgent: req.get('User-Agent'),
ip: req.ip
};
// 写入日志文件或发送到日志服务
fs.appendFile('user_actions.log', JSON.stringify(userAction) + '\n', (err) => {
if (err) console.error('日志写入失败:', err);
});
next();
});
// 跟踪特定用户事件
app.post('/track-event', (req, res) => {
const { userId, eventName, eventData } = req.body;
const eventLog = {
timestamp: new Date().toISOString(),
userId,
eventName,
eventData
};
// 发送到分析服务或写入数据库
logEventToDatabase(eventLog);
res.status(200).send('Event tracked');
});
方案 | 优点 | 缺点 | 适用场景 |
---|---|---|---|
文件日志 | 简单易用 | 难以查询分析 | 小型应用 |
MongoDB | 灵活查询 | 需要额外服务 | 中等规模 |
Elasticsearch | 强大搜索分析 | 复杂配置 | 大规模应用 |
专用服务(如Mixpanel) | 开箱即用 | 成本高 | 需要快速实现 |
const { Client } = require('@elastic/elasticsearch');
const client = new Client({ node: 'http://localhost:9200' });
async function logUserAction(action) {
try {
await client.index({
index: 'user-actions',
body: action
});
} catch (err) {
console.error('Elasticsearch 写入失败:', err);
}
}
// 使用Kibana可视化
// 先确保Elasticsearch数据已正确索引
// 或使用Node.js分析库
const analyzeFunnel = (events) => {
const steps = ['view', 'add_to_cart', 'checkout', 'purchase'];
const counts = {};
events.forEach(event => {
if (steps.includes(event.eventName)) {
counts[event.eventName] = (counts[event.eventName] || 0) + 1;
}
});
return steps.map(step => ({
step,
count: counts[step] || 0,
conversion: counts[step] / (counts[steps[0]] || 1)
}));
};
用户行为 → Node.js应用 → 日志中间件 →
→ 实时流处理(Kafka) → 分析引擎(Flink/Spark) →
→ 存储(ES/ClickHouse) → 可视化(Kibana/Grafana)
通过以上方法,您可以在Node.js应用中有效地收集、存储和分析用户行为数据,为产品决策提供有力支持。