标签: 网站建设
WEB-27:网站监控与告警设置
网站建设
5
<p><strong>网站监控与告警设置</strong> 是通过配置可用性监控、性能监控、错误追踪、日志分析,设置多级告警规则,确保网站问题及时发现、快速响应,最大限度减少停机时间和用户损失的系统化管理方法。</p>
<hr>
<h2>为什么需要监控?</h2>
<h3>监控价值</h3>
<p><strong>业务价值:</strong></p>
<pre><code>✅ 减少停机时间
✅ 快速发现问题
✅ 提升用户体验
✅ 数据驱动优化
</code></pre>
<p><strong>成本对比:</strong></p>
<pre><code>监控成本:每月几百元
停机损失:每分钟数千到数万
ROI:非常明显
</code></pre>
<h3>监控场景</h3>
<p><strong>可用性监控:</strong></p>
<pre><code>- 网站是否可访问
- 响应时间是否正常
- SSL 证书状态
- 域名到期提醒
</code></pre>
<p><strong>性能监控:</strong></p>
<pre><code>- 页面加载时间
- API 响应时间
- 数据库性能
- 服务器资源
</code></pre>
<p><strong>错误监控:</strong></p>
<pre><code>- 应用错误
- JavaScript 错误
- API 错误
- 数据库错误
</code></pre>
<hr>
<h2>可用性监控</h2>
<h3>监控工具选择 ⭐⭐⭐⭐⭐</h3>
<p><strong>国际工具:</strong></p>
<pre><code>1. Uptime Robot
- 免费 50 个监控
- 5 分钟检查
- 邮件/短信告警
- 推荐 ⭐⭐⭐⭐⭐
2. Pingdom
- 功能强大
- 详细报告
- $10/月起
3. StatusCake
- 免费 10 个监控
- 功能全面
- 性价比高
</code></pre>
<p><strong>国内工具:</strong></p>
<pre><code>1. 阿里云监控
- 免费额度
- 国内节点
- 与阿里云集成
2. 腾讯云监控
- 免费额度
- 国内节点
- 微信告警
3. 监控宝
- 专业监控
- 国内节点
- 付费
</code></pre>
<h3>配置监控 ⭐⭐⭐⭐⭐</h3>
<p><strong>Uptime Robot 配置:</strong></p>
<pre><code>1. 注册账号
- 访问 uptimerobot.com
- 免费注册
2. 添加监控
- Monitor Type: HTTP(s)
- Friendly Name: 网站名称
- URL: https://yourdomain.com
- Monitoring Interval: 5 minutes
3. 设置告警
- Add Alert Contact
- 邮箱/短信/微信
- 告警阈值
4. 确认配置
- 保存
- 开始监控
</code></pre>
<p><strong>多地点监控:</strong></p>
<pre><code>监控节点:
- 北京
- 上海
- 广州
- 美国
- 欧洲
优势:
- 发现区域性问题
- CDN 效果监控
- 全球可用性
</code></pre>
<h3>监控指标 ⭐⭐⭐⭐⭐</h3>
<p><strong>核心指标:</strong></p>
<pre><code>1. 可用性
- 目标:99.9%+
- 计算:正常运行时间/总时间
2. 响应时间
- 目标:<3 秒
- 警告:>5 秒
- 严重:>10 秒
3. SSL 状态
- 证书有效
- 到期提醒(30 天)
- 加密强度
</code></pre>
<p><strong>告警级别:</strong></p>
<pre><code>P0 - 网站不可用:立即电话
P1 - 响应慢:5 分钟内通知
P2 - SSL 即将到期:邮件通知
P3 - 性能下降:每日报告
</code></pre>
<hr>
<h2>性能监控</h2>
<h3>页面性能 ⭐⭐⭐⭐⭐</h3>
<p><strong>Google PageSpeed:</strong></p>
<pre><code class="language-javascript">// PageSpeed Insights API
const PSI_KEY = 'YOUR_API_KEY';
async function checkPageSpeed(url) {
const response = await fetch(
`https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=${url}&amp;key=${PSI_KEY}`
);
const data = await response.json();
return {
performance: data.lighthouseResult.categories.performance.score,
fcp: data.lighthouseResult.audits['first-contentful-paint'].numericValue,
lcp: data.lighthouseResult.audits['largest-contentful-paint'].numericValue,
cls: data.lighthouseResult.audits['cumulative-layout-shift'].numericValue
};
}
</code></pre>
<p><strong>性能指标:</strong></p>
<pre><code>Core Web Vitals:
- LCP (最大内容绘制): <2.5 秒
- FID (首次输入延迟): <100 毫秒
- CLS (累积布局偏移): <0.1
其他指标:
- FCP (首次内容绘制): <1.5 秒
- TTI (可交互时间): <3.5 秒
- TBT (总阻塞时间): <200 毫秒
</code></pre>
<h3>API 性能监控 ⭐⭐⭐⭐</h3>
<p><strong>监控实现:</strong></p>
<pre><code class="language-javascript">const axios = require('axios');
async function monitorAPI(endpoint) {
const start = Date.now();
try {
const response = await axios.get(endpoint, {
timeout: 5000
});
const responseTime = Date.now() - start;
return {
status: 'success',
statusCode: response.status,
responseTime: responseTime,
timestamp: new Date().toISOString()
};
} catch (error) {
return {
status: 'error',
error: error.message,
responseTime: Date.now() - start,
timestamp: new Date().toISOString()
};
}
}
// 定期监控
setInterval(async () => {
const result = await monitorAPI('https://api.example.com/health');
console.log(result);
// 发送告警
if (result.status === 'error' || result.responseTime > 1000) {
sendAlert(result);
}
}, 60000); // 每分钟
</code></pre>
<hr>
<h2>错误监控</h2>
<h3>应用错误 ⭐⭐⭐⭐⭐</h3>
<p><strong>Sentry 集成:</strong></p>
<pre><code class="language-javascript">// 安装
npm install @sentry/node
// 配置
const Sentry = require('@sentry/node');
Sentry.init({
dsn: 'YOUR_SENTRY_DSN',
environment: 'production',
tracesSampleRate: 1.0,
});
// 捕获错误
try {
// 可能出错的代码
} catch (error) {
Sentry.captureException(error);
}
// 自定义上下文
Sentry.configureScope(scope => {
scope.setUser({ id: user.id, email: user.email });
scope.setTag('page', 'checkout');
});
</code></pre>
<p><strong>前端错误监控:</strong></p>
<pre><code class="language-javascript">// 全局错误处理
window.onerror = function(message, source, lineno, colno, error) {
Sentry.captureException(error, {
extra: {
message: message,
source: source,
lineno: lineno,
colno: colno
}
});
};
// Promise 错误
window.onunhandledrejection = function(event) {
Sentry.captureException(event.reason);
};
</code></pre>
<h3>日志监控 ⭐⭐⭐⭐</h3>
<p><strong>日志收集:</strong></p>
<pre><code class="language-javascript">const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
// 使用
logger.info('用户登录', { userId: 123, ip: '192.168.1.1' });
logger.error('数据库连接失败', { error: err.message });
</code></pre>
<p><strong>日志分析:</strong></p>
<pre><code>关键错误:
- 数据库错误
- 认证失败
- 支付失败
- API 超时
告警规则:
- 错误率 > 1%:警告
- 错误率 > 5%:严重
- 特定错误:立即告警
</code></pre>
<hr>
<h2>服务器监控</h2>
<h3>资源监控 ⭐⭐⭐⭐⭐</h3>
<p><strong>监控指标:</strong></p>
<pre><code>CPU:
- 使用率:<70%
- 警告:>80%
- 严重:>90%
内存:
- 使用率:<80%
- 警告:>85%
- 严重:>95%
磁盘:
- 使用率:<80%
- 警告:>85%
- 严重:>90%
网络:
- 带宽使用
- 连接数
- 错误率
</code></pre>
<p><strong>监控脚本:</strong></p>
<pre><code class="language-bash">#!/bin/bash
# CPU 使用率
CPU=$(top -bn1 | grep &quot;Cpu(s)&quot; | awk '{print $2}' | cut -d'%' -f1)
# 内存使用率
MEMORY=$(free | grep Mem | awk '{printf(&quot;%.2f&quot;), $3/$2 * 100.0}')
# 磁盘使用率
DISK=$(df -h / | tail -1 | awk '{print $5}' | cut -d'%' -f1)
# 检查并告警
if (( $(echo &quot;$CPU > 80&quot; | bc -l) )); then
echo &quot;CPU 使用率过高:$CPU%&quot; | mail -s &quot;服务器告警&quot; admin@example.com
fi
if (( $(echo &quot;$MEMORY > 85&quot; | bc -l) )); then
echo &quot;内存使用率过高:$MEMORY%&quot; | mail -s &quot;服务器告警&quot; admin@example.com
fi
if [ $DISK -gt 85 ]; then
echo &quot;磁盘使用率过高:$DISK%&quot; | mail -s &quot;服务器告警&quot; admin@example.com
fi
</code></pre>
<h3>进程监控 ⭐⭐⭐⭐</h3>
<p><strong>进程监控:</strong></p>
<pre><code class="language-bash">#!/bin/bash
# 检查 Nginx
if ! pgrep -x &quot;nginx&quot; > /dev/null; then
echo &quot;Nginx 进程已停止&quot; | mail -s &quot;服务告警&quot; admin@example.com
systemctl start nginx
fi
# 检查 MySQL
if ! pgrep -x &quot;mysqld&quot; > /dev/null; then
echo &quot;MySQL 进程已停止&quot; | mail -s &quot;服务告警&quot; admin@example.com
systemctl start mysql
fi
# 检查 PHP-FPM
if ! pgrep -x &quot;php-fpm&quot; > /dev/null; then
echo &quot;PHP-FPM 进程已停止&quot; | mail -s &quot;服务告警&quot; admin@example.com
systemctl start php-fpm
fi
</code></pre>
<hr>
<h2>告警设置</h2>
<h3>告警渠道 ⭐⭐⭐⭐⭐</h3>
<p><strong>邮件告警:</strong></p>
<pre><code class="language-javascript">const nodemailer = require('nodemailer');
async function sendEmailAlert(subject, message) {
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS
}
});
await transporter.sendMail({
from: '监控 <monitor@example.com>',
to: 'admin@example.com',
subject: `[告警] ${subject}`,
text: message
});
}
</code></pre>
<p><strong>短信告警:</strong></p>
<pre><code class="language-javascript">// 阿里云短信
async function sendSMSAlert(phone, message) {
// 使用阿里云短信 API
const result = await client.sendSms({
PhoneNumbers: phone,
SignName: '网站监控',
TemplateCode: 'SMS_123456789',
TemplateParam: JSON.stringify({ message: message })
});
return result;
}
</code></pre>
<p><strong>即时通讯告警:</strong></p>
<pre><code class="language-javascript">// 企业微信
async function sendWechatAlert(message) {
const webhook = 'YOUR_WEBHOOK_URL';
await axios.post(webhook, {
msgtype: 'text',
text: {
content: `【网站告警】\n${message}`
}
});
}
// 钉钉
async function sendDingtalkAlert(message) {
const webhook = 'YOUR_WEBHOOK_URL';
await axios.post(webhook, {
msgtype: 'text',
text: {
content: `【网站告警】\n${message}`
}
});
}
</code></pre>
<h3>告警规则 ⭐⭐⭐⭐⭐</h3>
<p><strong>分级告警:</strong></p>
<pre><code>P0 - 严重(网站不可用):
- 渠道:电话 + 短信 + 即时通讯
- 响应:5 分钟内
- 升级:15 分钟未响应升级
P1 - 警告(性能下降):
- 渠道:短信 + 即时通讯
- 响应:30 分钟内
- 升级:1 小时未响应升级
P2 - 注意(潜在问题):
- 渠道:即时通讯
- 响应:4 小时内
- 升级:次日未处理升级
P3 - 信息(日常报告):
- 渠道:邮件
- 响应:每日查看
</code></pre>
<p><strong>告警升级:</strong></p>
<pre><code class="language-javascript">const escalationLevels = [
{ delay: 0, contacts: ['oncall@example.com'] },
{ delay: 15, contacts: ['team-lead@example.com'] },
{ delay: 30, contacts: ['manager@example.com'] },
{ delay: 60, contacts: ['cto@example.com'] }
];
async function sendEscalatingAlert(issue) {
for (const level of escalationLevels) {
setTimeout(() => {
if (!issue.resolved) {
sendAlert(level.contacts, issue);
}
}, level.delay * 60000);
}
}
</code></pre>
<hr>
<h2>监控仪表板</h2>
<h3>数据展示 ⭐⭐⭐⭐</h3>
<p><strong>Grafana 配置:</strong></p>
<pre><code>数据源:
- Prometheus
- MySQL
- Elasticsearch
仪表板:
- 可用性概览
- 性能指标
- 错误统计
- 资源使用
</code></pre>
<p><strong>关键指标展示:</strong></p>
<pre><code>1. 可用性
- 当前状态
- 7 天可用性
- 30 天可用性
2. 性能
- 平均响应时间
- P95 响应时间
- P99 响应时间
3. 错误
- 今日错误数
- 错误率
- 错误趋势
4. 资源
- CPU 使用率
- 内存使用率
- 磁盘使用率
</code></pre>
<hr>
<h2>王尘宇实战建议</h2>
<h3>18 年经验总结</h3>
<ol>
<li><strong>多层次监控</strong></li>
<li>可用性</li>
<li>性能</li>
<li>错误</li>
<li>
<p>资源</p>
</li>
<li>
<p><strong>合理告警</strong></p>
</li>
<li>分级告警</li>
<li>避免告警疲劳</li>
<li>
<p>升级机制</p>
</li>
<li>
<p><strong>快速响应</strong></p>
</li>
<li>值班制度</li>
<li>响应流程</li>
<li>
<p>问题追踪</p>
</li>
<li>
<p><strong>持续优化</strong></p>
</li>
<li>分析告警</li>
<li>优化阈值</li>
<li>
<p>减少误报</p>
</li>
<li>
<p><strong>文档记录</strong></p>
</li>
<li>监控配置</li>
<li>告警规则</li>
<li>响应流程</li>
</ol>
<h3>西安企业建议</h3>
<ul>
<li>选择国内监控服务</li>
<li>配置多级告警</li>
<li>建立响应机制</li>
<li>定期演练</li>
</ul>
<hr>
<h2>常见问题解答</h2>
<h3>Q1:监控间隔多久合适?</h3>
<p><strong>答:</strong><br>
- 可用性:1-5 分钟<br>
- 性能:5-15 分钟<br>
- 资源:1-5 分钟<br>
- 日志:实时</p>
<h3>Q2:如何避免告警疲劳?</h3>
<p><strong>答:</strong><br>
- 合理阈值<br>
- 分级告警<br>
- 告警聚合<br>
- 静默时间</p>
<h3>Q3:需要监控哪些指标?</h3>
<p><strong>答:</strong><br>
- 可用性(必须)<br>
- 响应时间(必须)<br>
- 错误率(必须)<br>
- 资源使用(推荐)</p>
<h3>Q4:告警发给谁?</h3>
<p><strong>答:</strong><br>
- 值班人员<br>
- 技术负责人<br>
- 升级机制<br>
- 轮班制度</p>
<h3>Q5:监控成本多少?</h3>
<p><strong>答:</strong><br>
- 免费工具:0 元<br>
- 基础付费:100-500 元/月<br>
- 企业级:1000 元+/月<br>
- 根据需求</p>
<hr>
<h2>总结</h2>
<p>网站监控与告警设置核心要点:</p>
<ul>
<li>📊 <strong>可用性监控</strong> — 多地点、多工具</li>
<li>⚡ <strong>性能监控</strong> — 页面、API、资源</li>
<li>🐛 <strong>错误监控</strong> — 应用、前端、日志</li>
<li>📱 <strong>告警设置</strong> — 多渠道、分级、升级</li>
<li>📈 <strong>仪表板</strong> — 数据展示、可视化</li>
</ul>
<p><strong>王尘宇建议:</strong> 监控是网站健康的眼睛。建立完善的监控体系,及时发现问题,快速响应处理。</p>
<hr>
<h2>关于作者</h2>
<p><strong>王尘宇</strong><br>
西安蓝蜻蜓网络科技有限公司创始人 </p>
<p><strong>联系方式:</strong><br>
- 🌐 网站:<a href="https://wangchenyu.com">wangchenyu.com</a><br>
- 💬 微信:wangshifucn<br>
- 📱 QQ:314111741<br>
- 📍 地址:陕西西安</p>
<hr>
<p><em>本文最后更新:2026 年 3 月 18 日</em><br>
<em>版权声明:本文为王尘宇原创,属于"网站建设系列"第 27 篇,转载请联系作者并注明出处。</em><br>
<em>下一篇:WEB-28:网站日志分析方法</em></p>
还木有评论哦,快来抢沙发吧~