当前位置:网站首页 >  攻略

从零搭建网站与应用流量变现全链路监控系统 三步落地实时数据

时间:2026年06月08日 03:33:29 来源:易频IT社区

准备工作:选工具、填配置、启环境

本次用开源三件套:Prometheus+Grafana+Node Exporter(通用版),适配90%以上接入广告SDK/联盟的网站、App(后端改下Exporter也能用,但先从通用版学,后端补全见文末)

1. 安装Docker(一键式,卡壳直接用这个)

不管你是Windows/Mac/Linux,先装Docker Desktop(Mac/Windows)或Docker CE(Linux),Linux用这个一键脚本:

```bash curl -fsSL https://get.docker.com -o get-docker.sh sudo sh get-docker.sh sudo usermod -aG docker $USER ```

重启终端后验证:

```bash docker --version docker-compose --version ```

2. 写Docker Compose配置文件(可直接复制)

找个空文件夹,新建docker-compose.yml,粘贴以下完整内容:

```yaml version: '3.8' services: prometheus: image: prom/prometheus:v2.52.0 container_name: prometheus ports: - "9090:9090" volumes: - ./prometheus.yml:/etc/prometheus/prometheus.yml - prometheus_data:/prometheus restart: always grafana: image: grafana/grafana:11.0.0 container_name: grafana ports: - "3000:3000" volumes: - grafana_data:/var/lib/grafana restart: always depends_on: - prometheus node_exporter: image: prom/node-exporter:v1.8.2 container_name: node_exporter ports: - "9100:9100" restart: always volumes: - /proc:/host/proc:ro - /sys:/host/sys:ro - /:/rootfs:ro command: - '--path.procfs=/host/proc' - '--path.sysfs=/host/sys' - '--path.rootfs=/rootfs' - '--collector.filesystem.mount-points-exclude=^/(sys|proc|dev|host|etc)($$|/)' volumes: prometheus_data: grafana_data: ```

3. 写Prometheus基础数据采集配置(可直接复制)

从零搭建网站与应用流量变现全链路监控系统 三步落地实时数据

同文件夹新建prometheus.yml,粘贴以下内容,联盟/SDK数据我们后面用静态JSON或者HTTP接口对接(本次先讲静态模拟,HTTP接口见后续拓展):

```yaml global: scrape_interval: 15s 采集间隔,按需改短/长 scrape_configs: - job_name: 'node_exporter' 监控服务器资源,避免因资源不足掉广告 static_configs: - targets: ['node_exporter:9100'] - job_name: 'mock_ad_revenue' 模拟广告SDK上报的变现数据 static_configs: - targets: ['localhost:9101'] 后面我们自己开个端口传模拟数据 metrics_path: '/metrics' ```

第一步:启动开源三件套基础环境

  • 在刚才的文件夹打开终端,输入启动命令: ```bash docker-compose up -d ```
  • 验证:浏览器依次访问http://你的服务器IP:9090/targets(本地localhost)、http://你的服务器IP:3000(本地localhost),Prometheus的targets里node_exporter必须显示UP
  • Grafana初始账号密码都是admin,首次登录强制改密码

第二步:接入真实/模拟广告变现数据

真实数据用联盟/SDK的API(比如穿山甲、优量汇、AdSense都有),本次先写1个Python3模拟上报脚本(可直接复制运行,快速看效果):

1. 安装Python依赖

```bash pip3 install prometheus-client ```

2. 写模拟数据上报脚本mock_ad_metrics.py

```python from prometheus_client import start_http_server, Gauge import time import random 定义4个核心变现指标 DAILY_ACTIVE_USERS = Gauge('ad_daily_active_users', '日活用户数') AD_REQUESTS = Gauge('ad_requests_total', '广告请求总数') AD_IMPRESSIONS = Gauge('ad_impressions_total', '广告曝光总数') AD_REVENUE = Gauge('ad_revenue_total', '广告总收入(元)') 初始化模拟数据基数 dau = 10000 ad_req = 0 ad_imp = 0 ad_rev = 0 if __name__ == '__main__': start_http_server(9101) 对应prometheus.yml里的9101端口 print("模拟广告变现数据已上报到 http://localhost:9101/metrics") while True: 每15秒更新一次数据(和prometheus采集间隔一致) dau += random.randint(-100, 200) delta_req = random.randint(500, 1500) ad_req += delta_req delta_imp = random.randint(int(delta_req0.6), int(delta_req0.85)) ad_imp += delta_imp delta_rev = random.randint(5, 20) 模拟ecpm0.5-2元左右 ad_rev += delta_rev/100 DAILY_ACTIVE_USERS.set(dau) AD_REQUESTS.set(ad_req) AD_IMPRESSIONS.set(ad_imp) AD_REVENUE.set(ad_rev) time.sleep(15) ```

3. 运行脚本并验证Prometheus采集

  • 后台运行脚本: ```bash nohup python3 mock_ad_metrics.py > mock_ad.log 2>&1 & ```
  • 过30秒刷新Prometheus的targets页面,mock_ad_revenue必须显示UP
  • 在Prometheus的Graph页面输入ad_revenue_total,点击Execute,能看到上升曲线就成功了

第三步:配置Grafana变现数据看板与告警

1. 配置Grafana数据源

  • 登录Grafana,点击左侧ConnectionsData sourcesAdd data source
  • 选择Prometheus,在HTTP URL栏输入http://prometheus:9090(因为是Docker网络,不用填服务器IP)
  • 拉到最下面点击Save & test,显示绿色“Data source is working”就成功了

2. 一键导入现成的广告变现看板(避免自己搭浪费时间)

点击左侧DashboardsNewImport,粘贴Grafana官方现成的通用Exporter+自定义指标的ID?不对,本次用自定义指标,直接给个简单的JSON配置片段,粘贴到Import via panel json框里:

```json { "annotations": { "list": [] }, "editable": true, "fiscalYearStartMonth": 0, "graphTooltip": 0, "id": null, "links": [], "liveNow": false, "panels": [ { "datasource": { "type": "prometheus", "uid": "pbprometheus" }, "fieldConfig": { "defaults": { "color": { "mode": "thresholds" }, "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": null } ] }, "unit": "short" }, "overrides": [] }, "gridPos": { "h": 4, "w": 6, "x": 0, "y": 0 }, "id": 1, "options": { "colorMode": "value", "graphMode": "area", "justifyMode": "auto", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false }, "textMode": "auto" }, "targets": [ { "expr": "ad_daily_active_users", "refId": "A" } ], "title": "日活用户数", "type": "stat" }, { "datasource": { "type": "prometheus", "uid": "pbprometheus" }, "fieldConfig": { "defaults": { "color": { "mode": "thresholds" }, "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": null } ] }, "unit": "short" }, "overrides": [] }, "gridPos": { "h": 4, "w": 6, "x": 6, "y": 0 }, "id": 2, "options": { "colorMode": "value", "graphMode": "area", "justifyMode": "auto", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false }, "textMode": "auto" }, "targets": [ { "expr": "ad_impressions_total / ad_requests_total 100", "refId": "A" } ], "title": "广告填充率(%)", "type": "stat" }, { "datasource": { "type": "prometheus", "uid": "pbprometheus" }, "fieldConfig": { "defaults": { "color": { "mode": "thresholds" }, "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": null } ] }, "unit": "currencyCNY" }, "overrides": [] }, "gridPos": { "h": 4, "w": 6, "x": 12, "y": 0 }, "id": 3, "options": { "colorMode": "value", "graphMode": "area", "justifyMode": "auto", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false }, "textMode": "auto" }, "targets": [ { "expr": "ad_revenue_total", "refId": "A" } ], "title": "今日累计收入(元)", "type": "stat" }, { "datasource": { "type": "prometheus", "uid": "pbprometheus" }, "fieldConfig": { "defaults": { "color": { "mode": "palette-classic" }, "custom": { "axisBorderShow": false, "axisCenteredZero": false, "axisColorMode": "text", "axisLabel": "", "axisPlacement": "auto", "barAlignment": 0, "drawStyle": "line", "fillOpacity": 10, "gradientMode": "none", "hideFrom": { "legend": false, "tooltip": false, "viz": false }, "insertNulls": false, "lineInterpolation": "linear", "lineWidth": 1, "pointSize": 5, "scaleDistribution": { "type": "linear" }, "showPoints": "auto", "spanNulls": false, "stacking": { "group": "A", "mode": "none" }, "thresholdsStyle": { "mode": "off" } }, "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": null } ] } }, "overrides": [] }, "gridPos": { "h": 8, "w": 24, "x": 0, "y": 4 }, "id": 4, "options": { "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": true }, "tooltip": { "mode": "single", "sort": "none" } }, "targets": [ { "expr": "rate(ad_revenue_total[1h])", "legendFormat": "每小时收入(元)", "refId": "A" } ], "title": "每小时收入趋势", "type": "timeseries" } ], "refresh": "5s", "schemaVersion": 39, "tags": [], "templating": { "list": [] }, "time": { "from": "now-24h", "to": "now" }, "timepicker": {}, "timezone": "", "title": "广告变现全链路监控看板", "uid": "admonboard", "version": 1, "weekStart": "" } ```
  • 注意:如果之前配置的Prometheus数据源UID不是pbprometheus,就手动选一下刚才保存的数据源
  • 点击Import,就能看到实时更新的看板了

3. 配置填充率低于50%的告警(钉钉/微信机器人都能用,但本次先讲Grafana自带的邮箱告警)

  • 点击左侧AlertingContact pointsNew contact point
  • Name填“邮箱告警”,Integration选“Email”,Addresses填你的邮箱,点击Save contact point
  • 点击左侧AlertingAlert rulesNew alert rule
  • Rule name填“广告填充率告警”,Query选刚才的Prometheus数据源,Metric输入ad_impressions_total / ad_requests_total 100,Condition选“Below”,Value填50
  • For填“1m”(连续1分钟低于50%才告警,避免误报),Notification选刚才的“邮箱告警”,点击Save rule

拓展:如何接入真实联盟API数据

以AdSense为例,用Google Ads Python SDK替换刚才的模拟脚本,步骤是:

  1. 去Google Cloud Console创建项目,启用AdSense Management API v2
  2. 生成OAuth2.0客户端密钥JSON文件,命名为ads

相关推荐

最新

热门

推荐

精选

标签

易频IT社区是综合性互联网IT技术门户网站,专注分享网络技术、服务器运维、网络安全、编程开发、系统架构、云计算、大数据等行业干货,实时更新IT行业资讯、零基础教程、实战案例,为IT从业者、技术爱好者提供专业的学习交流平台。

Copyright © 2021-2026 易频IT社区. All Rights Reserved. 备案号:闽ICP备2023013482号 网站地图