[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"blog-post-cn-jiankong-daili-xingneng":3},{"success":4,"payload":5,"related":78,"errors":148},true,{"id":6,"slug":7,"title":8,"excerpt":9,"body_html":10,"meta_title":8,"meta_description":11,"canonical_url":12,"canonical_override":13,"og_title":8,"og_description":11,"og_image_url":14,"faq_json":15,"key_takeaways":31,"allow_index":37,"noindex_google_only":37,"allow_follow":4,"published_at":38,"updated_at":39,"content_updated_at":40,"featured_image_url":41,"featured_image_alt":13,"card_image_url":42,"reading_time_minutes":43,"author":44,"categories":48,"tags":55,"alternates":64,"locale_paths":76,"views":77},41,"jiankong-daili-xingneng","监控代理性能：延迟、成功率和告警","学习如何对代理性能进行仪表、监控和警报——跟踪延迟百分位数、成功率、错误模式和带宽。 Python、Node.js和Go的代码示例.","\u003Ch2>为什么监视代理性能\u003C\u002Fh2>\u003Cp>代理基础设施无声失败. 你的刮刮机可能会运行数小时,成功率在任何人注意到之前达到40%. 反应时间逐渐上升,块速率上升,数据质量下降——这一切都没有引起明显的错误. 监测将这些看不见的问题变成可采取行动的警报。\u003C\u002Fp>\u003Cp>本指南向您介绍如何记录您的代理请求, 收集有意义的度量衡, 构建仪表板, 并设置提醒, 捕获退化 之前影响您的数据管道。 所有实例都使用 \u003Ca href=\"\u002Fcn\u002Fblog\u002Fzuijia-wangluo-caiji-daili-2026\">代理哈特的住宅代理\u003C\u002Fa> 并做好了生产准备。\u003C\u002Fp>\u003Cblockquote>如果你不是在测量你的代理性能,你是在猜测。 估计规模需要钱,产生不可靠的数据。\u003C\u002Fblockquote>\u003Ch2>音轨密钥量表\u003C\u002Fh2>\u003Ctable>\n\u003Ccaption>音轨密钥量表\u003C\u002Fcaption>\u003Cthead>\u003Ctr>\u003Cth>度量衡\u003C\u002Fth>\u003Cth>它告诉你什么\u003C\u002Fth>\u003Cth>警戒阈值\u003C\u002Fth>\u003C\u002Ftr>\u003C\u002Fthead>\u003Ctbody>\u003Ctr>\u003Ctd>成功率\u003C\u002Ftd>\u003Ctd>回复2xx状态的申请百分比\u003C\u002Ftd>\u003Ctd>低于90%\u003C\u002Ftd>\u003C\u002Ftr>\u003Ctr>\u003Ctd>应急反应(p50\u002Fp95\u002Fp99)\u003C\u002Ftd>\u003Ctd>代理请求完成的速度\u003C\u002Ftd>\u003Ctd>p95以上10个\u003C\u002Ftd>\u003C\u002Ftr>\u003Ctr>\u003Ctd>按类型分列的错误率\u003C\u002Ftd>\u003Ctd>哪些错误占主导地位( 超时, 403, 429, 连接)\u003C\u002Ftd>\u003Ctd>15%以上的任何单一类型\u003C\u002Ftd>\u003C\u002Ftr>\u003Ctr>\u003Ctd>每秒请求数\u003C\u002Ftd>\u003Ctd>管道的流量\u003C\u002Ftd>\u003Ctd>低于预期基线\u003C\u002Ftd>\u003C\u002Ftr>\u003Ctr>\u003Ctd>带宽使用\u003C\u002Ftd>\u003Ctd>通过代理传输的数据\u003C\u002Ftd>\u003Ctd>接近计划限额\u003C\u002Ftd>\u003C\u002Ftr>\u003Ctr>\u003Ctd>按目标分列的区块率\u003C\u002Ftd>\u003Ctd>哪个目标最能挡住你\u003C\u002Ftd>\u003Ctd>目标超过20%\u003C\u002Ftd>\u003C\u002Ftr>\u003Ctr>\u003Ctd>重试率\u003C\u002Ftd>\u003Ctd>需要重审的请求数\u003C\u002Ftd>\u003Ctd>超过30%\u003C\u002Ftd>\u003C\u002Ftr>\u003Ctr>\u003Ctd>会话重复使用效率\u003C\u002Ftd>\u003Ctd>粘糊糊的会话能活多久\u003C\u002Ftd>\u003Ctd>5项请求平均数以下\u003C\u002Ftd>\u003C\u002Ftr>\u003C\u002Ftbody>\u003C\u002Ftable>\u003Ch2>Python: 仪器代理客户端\u003C\u002Fh2>\u003Cp>这个客户端以时间,状态跟踪,以及结构化的日志来包裹每个请求.\u003C\u002Fp>\u003Cpre>\u003Ccode>import time\nimport uuid\nimport logging\nimport statistics\nfrom dataclasses import dataclass, field\nfrom collections import defaultdict\nfrom typing import Optional\nimport requests\nlogger = logging.getLogger(\"proxy_monitor\")\n@dataclass\nclass ProxyMetrics:\n    \"\"\"Collects and aggregates proxy performance metrics.\"\"\"\n    total_requests: int = 0\n    successful: int = 0\n    failed: int = 0\n    retries: int = 0\n    latencies: list = field(default_factory=list)\n    status_codes: dict = field(default_factory=lambda: defaultdict(int))\n    errors_by_type: dict = field(default_factory=lambda: defaultdict(int))\n    bytes_transferred: int = 0\n    requests_by_target: dict = field(default_factory=lambda: defaultdict(lambda: {\"success\": 0, \"failed\": 0}))\n    @property\n    def success_rate(self) -> float:\n        return (self.successful \u002F self.total_requests * 100) if self.total_requests > 0 else 0.0\n    @property\n    def p50_latency(self) -> float:\n        return statistics.median(self.latencies) if self.latencies else 0.0\n    @property\n    def p95_latency(self) -> float:\n        if not self.latencies:\n            return 0.0\n        sorted_lat = sorted(self.latencies)\n        idx = int(len(sorted_lat) * 0.95)\n        return sorted_lat[min(idx, len(sorted_lat) - 1)]\n    @property\n    def p99_latency(self) -> float:\n        if not self.latencies:\n            return 0.0\n        sorted_lat = sorted(self.latencies)\n        idx = int(len(sorted_lat) * 0.99)\n        return sorted_lat[min(idx, len(sorted_lat) - 1)]\n    def summary(self) -> dict:\n        return {\n            \"total_requests\": self.total_requests,\n            \"success_rate\": f\"{self.success_rate:.1f}%\",\n            \"p50_latency\": f\"{self.p50_latency:.3f}s\",\n            \"p95_latency\": f\"{self.p95_latency:.3f}s\",\n            \"p99_latency\": f\"{self.p99_latency:.3f}s\",\n            \"retries\": self.retries,\n            \"bytes_transferred\": self.bytes_transferred,\n            \"top_errors\": dict(sorted(\n                self.errors_by_type.items(),\n                key=lambda x: x[1], reverse=True\n            )[:5]),\n            \"status_distribution\": dict(self.status_codes),\n        }\nclass MonitoredProxyClient:\n    \"\"\"HTTP client with built-in proxy monitoring.\"\"\"\n    def __init__(self, max_retries: int = 3):\n        self.metrics = ProxyMetrics()\n        self.max_retries = max_retries\n        self._alert_callbacks = []\n    def on_alert(self, callback):\n        \"\"\"Register a callback for metric alerts.\"\"\"\n        self._alert_callbacks.append(callback)\n    def _check_alerts(self):\n        if self.metrics.total_requests \u003C 10:\n            return\n        alerts = []\n        if self.metrics.success_rate \u003C 90:\n            alerts.append(f\"Low success rate: {self.metrics.success_rate:.1f}%\")\n        if self.metrics.p95_latency > 10:\n            alerts.append(f\"High p95 latency: {self.metrics.p95_latency:.1f}s\")\n        if self.metrics.retries \u002F max(self.metrics.total_requests, 1) > 0.3:\n            alerts.append(f\"High retry rate: {self.metrics.retries}\u002F{self.metrics.total_requests}\")\n        for alert in alerts:\n            logger.warning(f\"ALERT: {alert}\")\n            for cb in self._alert_callbacks:\n                cb(alert)\n    def fetch(self, url: str, country: Optional[str] = None) -> Optional[requests.Response]:\n        from urllib.parse import urlparse\n        target_domain = urlparse(url).netloc\n        for attempt in range(self.max_retries + 1):\n            session_id = uuid.uuid4().hex[:8]\n            username = f\"USERNAME-sid-{session_id}\"\n            if country:\n                username += f\"-country-{country}\"\n            proxy = f\"http:\u002F\u002F{username}:PASSWORD@gate.proxyhat.com:8080\"\n            self.metrics.total_requests += 1\n            if attempt > 0:\n                self.metrics.retries += 1\n            start = time.time()\n            try:\n                response = requests.get(\n                    url,\n                    proxies={\"http\": proxy, \"https\": proxy},\n                    timeout=30,\n                )\n                latency = time.time() - start\n                self.metrics.latencies.append(latency)\n                self.metrics.status_codes[response.status_code] += 1\n                if response.status_code >= 400:\n                    self.metrics.errors_by_type[f\"HTTP_{response.status_code}\"] += 1\n                    self.metrics.requests_by_target[target_domain][\"failed\"] += 1\n                    if response.status_code in (403, 429, 503) and attempt \u003C self.max_retries:\n                        time.sleep(2 ** attempt)\n                        continue\n                    self.metrics.failed += 1\n                else:\n                    self.metrics.successful += 1\n                    self.metrics.bytes_transferred += len(response.content)\n                    self.metrics.requests_by_target[target_domain][\"success\"] += 1\n                self._check_alerts()\n                return response\n            except requests.exceptions.Timeout:\n                self.metrics.errors_by_type[\"timeout\"] += 1\n                self.metrics.latencies.append(time.time() - start)\n                self.metrics.requests_by_target[target_domain][\"failed\"] += 1\n            except requests.exceptions.ConnectionError:\n                self.metrics.errors_by_type[\"connection_error\"] += 1\n                self.metrics.latencies.append(time.time() - start)\n                self.metrics.requests_by_target[target_domain][\"failed\"] += 1\n            except Exception as e:\n                self.metrics.errors_by_type[type(e).__name__] += 1\n                self.metrics.latencies.append(time.time() - start)\n            if attempt \u003C self.max_retries:\n                time.sleep(2 ** attempt)\n        self.metrics.failed += 1\n        self._check_alerts()\n        return None\n# Usage\nclient = MonitoredProxyClient(max_retries=3)\nclient.on_alert(lambda msg: print(f\"[ALERT] {msg}\"))\nurls = [f\"https:\u002F\u002Fexample.com\u002Fproduct\u002F{i}\" for i in range(100)]\nfor url in urls:\n    response = client.fetch(url)\nprint(client.metrics.summary())\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Ch2>节点.js:有仪器的代理客户端\u003C\u002Fh2>\u003Cpre>\u003Ccode>const crypto = require('crypto');\nconst { HttpsProxyAgent } = require('https-proxy-agent');\nconst { EventEmitter } = require('events');\nclass ProxyMetrics {\n  constructor() {\n    this.totalRequests = 0;\n    this.successful = 0;\n    this.failed = 0;\n    this.retries = 0;\n    this.latencies = [];\n    this.statusCodes = {};\n    this.errorsByType = {};\n    this.bytesTransferred = 0;\n    this.requestsByTarget = {};\n  }\n  get successRate() {\n    return this.totalRequests > 0\n      ? ((this.successful \u002F this.totalRequests) * 100).toFixed(1)\n      : '0.0';\n  }\n  percentile(p) {\n    if (this.latencies.length === 0) return 0;\n    const sorted = [...this.latencies].sort((a, b) => a - b);\n    const idx = Math.min(\n      Math.floor(sorted.length * (p \u002F 100)),\n      sorted.length - 1\n    );\n    return sorted[idx];\n  }\n  summary() {\n    return {\n      totalRequests: this.totalRequests,\n      successRate: `${this.successRate}%`,\n      p50Latency: `${this.percentile(50).toFixed(3)}s`,\n      p95Latency: `${this.percentile(95).toFixed(3)}s`,\n      p99Latency: `${this.percentile(99).toFixed(3)}s`,\n      retries: this.retries,\n      bytesTransferred: this.bytesTransferred,\n      statusDistribution: { ...this.statusCodes },\n      topErrors: Object.entries(this.errorsByType)\n        .sort(([, a], [, b]) => b - a)\n        .slice(0, 5)\n        .reduce((obj, [k, v]) => ({ ...obj, [k]: v }), {}),\n    };\n  }\n}\nclass MonitoredProxyClient extends EventEmitter {\n  constructor({ maxRetries = 3 } = {}) {\n    super();\n    this.metrics = new ProxyMetrics();\n    this.maxRetries = maxRetries;\n  }\n  _checkAlerts() {\n    if (this.metrics.totalRequests \u003C 10) return;\n    if (parseFloat(this.metrics.successRate) \u003C 90) {\n      this.emit('alert', `Low success rate: ${this.metrics.successRate}%`);\n    }\n    if (this.metrics.percentile(95) > 10) {\n      this.emit('alert', `High p95 latency: ${this.metrics.percentile(95).toFixed(1)}s`);\n    }\n  }\n  async fetch(url, { country } = {}) {\n    const targetDomain = new URL(url).hostname;\n    for (let attempt = 0; attempt \u003C= this.maxRetries; attempt++) {\n      const sessionId = crypto.randomBytes(4).toString('hex');\n      let username = `USERNAME-sid-${sessionId}`;\n      if (country) username += `-country-${country}`;\n      const agent = new HttpsProxyAgent(\n        `http:\u002F\u002F${username}:PASSWORD@gate.proxyhat.com:8080`\n      );\n      this.metrics.totalRequests++;\n      if (attempt > 0) this.metrics.retries++;\n      const startTime = Date.now();\n      try {\n        const response = await fetch(url, {\n          agent,\n          signal: AbortSignal.timeout(30000),\n        });\n        const latency = (Date.now() - startTime) \u002F 1000;\n        this.metrics.latencies.push(latency);\n        this.metrics.statusCodes[response.status] =\n          (this.metrics.statusCodes[response.status] || 0) + 1;\n        if (response.status >= 400) {\n          this.metrics.errorsByType[`HTTP_${response.status}`] =\n            (this.metrics.errorsByType[`HTTP_${response.status}`] || 0) + 1;\n          if ([403, 429, 503].includes(response.status) && attempt \u003C this.maxRetries) {\n            await new Promise(r => setTimeout(r, 1000 * Math.pow(2, attempt)));\n            continue;\n          }\n          this.metrics.failed++;\n        } else {\n          this.metrics.successful++;\n          const body = await response.text();\n          this.metrics.bytesTransferred += body.length;\n        }\n        this._checkAlerts();\n        return response;\n      } catch (err) {\n        const latency = (Date.now() - startTime) \u002F 1000;\n        this.metrics.latencies.push(latency);\n        this.metrics.errorsByType[err.name] =\n          (this.metrics.errorsByType[err.name] || 0) + 1;\n        if (attempt \u003C this.maxRetries) {\n          await new Promise(r => setTimeout(r, 1000 * Math.pow(2, attempt)));\n          continue;\n        }\n        this.metrics.failed++;\n      }\n    }\n    this._checkAlerts();\n    return null;\n  }\n}\n\u002F\u002F Usage\nconst client = new MonitoredProxyClient({ maxRetries: 3 });\nclient.on('alert', msg => console.warn(`[ALERT] ${msg}`));\nconst urls = Array.from({ length: 100 }, (_, i) =>\n  `https:\u002F\u002Fexample.com\u002Fproduct\u002F${i + 1}`\n);\nfor (const url of urls) {\n  await client.fetch(url);\n}\nconsole.log(client.metrics.summary());\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Ch2>Go: 设备化代理客户端\u003C\u002Fh2>\u003Cpre>\u003Ccode>package main\nimport (\n\t\"crypto\u002Frand\"\n\t\"encoding\u002Fhex\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n\t\"net\u002Fhttp\"\n\t\"net\u002Furl\"\n\t\"sort\"\n\t\"sync\"\n\t\"time\"\n)\ntype Metrics struct {\n\tmu             sync.Mutex\n\tTotalRequests  int\n\tSuccessful     int\n\tFailed         int\n\tRetries        int\n\tLatencies      []float64\n\tStatusCodes    map[int]int\n\tErrorsByType   map[string]int\n\tBytesTransferred int64\n}\nfunc NewMetrics() *Metrics {\n\treturn &Metrics{\n\t\tStatusCodes:  make(map[int]int),\n\t\tErrorsByType: make(map[string]int),\n\t}\n}\nfunc (m *Metrics) RecordSuccess(latency float64, status int, bytes int) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tm.TotalRequests++\n\tm.Successful++\n\tm.Latencies = append(m.Latencies, latency)\n\tm.StatusCodes[status]++\n\tm.BytesTransferred += int64(bytes)\n}\nfunc (m *Metrics) RecordFailure(latency float64, errType string) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tm.TotalRequests++\n\tm.Failed++\n\tm.Latencies = append(m.Latencies, latency)\n\tm.ErrorsByType[errType]++\n}\nfunc (m *Metrics) Percentile(p float64) float64 {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tif len(m.Latencies) == 0 {\n\t\treturn 0\n\t}\n\tsorted := make([]float64, len(m.Latencies))\n\tcopy(sorted, m.Latencies)\n\tsort.Float64s(sorted)\n\tidx := int(math.Min(float64(len(sorted)-1), float64(len(sorted))*p\u002F100))\n\treturn sorted[idx]\n}\nfunc (m *Metrics) SuccessRate() float64 {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tif m.TotalRequests == 0 {\n\t\treturn 0\n\t}\n\treturn float64(m.Successful) \u002F float64(m.TotalRequests) * 100\n}\nfunc (m *Metrics) Summary() string {\n\treturn fmt.Sprintf(\n\t\t\"Requests: %d | Success: %.1f%% | p50: %.3fs | p95: %.3fs | p99: %.3fs | Retries: %d\",\n\t\tm.TotalRequests, m.SuccessRate(),\n\t\tm.Percentile(50), m.Percentile(95), m.Percentile(99),\n\t\tm.Retries,\n\t)\n}\ntype MonitoredClient struct {\n\tmetrics    *Metrics\n\tmaxRetries int\n}\nfunc NewMonitoredClient(maxRetries int) *MonitoredClient {\n\treturn &MonitoredClient{\n\t\tmetrics:    NewMetrics(),\n\t\tmaxRetries: maxRetries,\n\t}\n}\nfunc (c *MonitoredClient) Fetch(target string) (*http.Response, error) {\n\tfor attempt := 0; attempt \u003C= c.maxRetries; attempt++ {\n\t\tb := make([]byte, 4)\n\t\trand.Read(b)\n\t\tsessionID := hex.EncodeToString(b)\n\t\tproxyStr := fmt.Sprintf(\n\t\t\t\"http:\u002F\u002FUSERNAME-sid-%s:PASSWORD@gate.proxyhat.com:8080\",\n\t\t\tsessionID,\n\t\t)\n\t\tproxyURL, _ := url.Parse(proxyStr)\n\t\tclient := &http.Client{\n\t\t\tTransport: &http.Transport{Proxy: http.ProxyURL(proxyURL)},\n\t\t\tTimeout:   30 * time.Second,\n\t\t}\n\t\tif attempt > 0 {\n\t\t\tc.metrics.mu.Lock()\n\t\t\tc.metrics.Retries++\n\t\t\tc.metrics.mu.Unlock()\n\t\t}\n\t\tstart := time.Now()\n\t\tresp, err := client.Get(target)\n\t\tlatency := time.Since(start).Seconds()\n\t\tif err != nil {\n\t\t\tc.metrics.RecordFailure(latency, \"connection_error\")\n\t\t\tif attempt \u003C c.maxRetries {\n\t\t\t\ttime.Sleep(time.Duration(math.Pow(2, float64(attempt))) * time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\tbody, _ := io.ReadAll(resp.Body)\n\t\tresp.Body.Close()\n\t\tif resp.StatusCode >= 400 {\n\t\t\tc.metrics.RecordFailure(latency, fmt.Sprintf(\"HTTP_%d\", resp.StatusCode))\n\t\t\tif attempt \u003C c.maxRetries {\n\t\t\t\ttime.Sleep(time.Duration(math.Pow(2, float64(attempt))) * time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else {\n\t\t\tc.metrics.RecordSuccess(latency, resp.StatusCode, len(body))\n\t\t}\n\t\treturn resp, nil\n\t}\n\treturn nil, fmt.Errorf(\"all retries exhausted for %s\", target)\n}\nfunc main() {\n\tclient := NewMonitoredClient(3)\n\tfor i := 0; i \u003C 50; i++ {\n\t\turl := fmt.Sprintf(\"https:\u002F\u002Fexample.com\u002Fproduct\u002F%d\", i+1)\n\t\tclient.Fetch(url)\n\t}\n\tfmt.Println(client.metrics.Summary())\n}\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Ch2>代理请求的结构化日志\u003C\u002Fh2>\u003Cp>JSON结构的日志便于汇总和分析分布式刮刮机的代理性能.\u003C\u002Fp>\u003Cpre>\u003Ccode>import json\nimport logging\nimport time\nimport uuid\nimport requests\nclass JSONProxyLogger:\n    \"\"\"Logs every proxy request as structured JSON.\"\"\"\n    def __init__(self, log_file: str = \"proxy_requests.jsonl\"):\n        self.logger = logging.getLogger(\"proxy_json\")\n        handler = logging.FileHandler(log_file)\n        handler.setFormatter(logging.Formatter(\"%(message)s\"))\n        self.logger.addHandler(handler)\n        self.logger.setLevel(logging.INFO)\n    def log_request(self, entry: dict):\n        self.logger.info(json.dumps(entry))\n    def fetch(self, url: str, country: str = None) -> requests.Response:\n        session_id = uuid.uuid4().hex[:8]\n        username = f\"USERNAME-sid-{session_id}\"\n        if country:\n            username += f\"-country-{country}\"\n        proxy = f\"http:\u002F\u002F{username}:PASSWORD@gate.proxyhat.com:8080\"\n        start = time.time()\n        try:\n            response = requests.get(\n                url,\n                proxies={\"http\": proxy, \"https\": proxy},\n                timeout=30,\n            )\n            latency = time.time() - start\n            self.log_request({\n                \"timestamp\": time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()),\n                \"url\": url,\n                \"status\": response.status_code,\n                \"latency_ms\": round(latency * 1000),\n                \"bytes\": len(response.content),\n                \"session_id\": session_id,\n                \"country\": country,\n                \"success\": response.status_code \u003C 400,\n            })\n            return response\n        except Exception as e:\n            latency = time.time() - start\n            self.log_request({\n                \"timestamp\": time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()),\n                \"url\": url,\n                \"error\": str(e),\n                \"error_type\": type(e).__name__,\n                \"latency_ms\": round(latency * 1000),\n                \"session_id\": session_id,\n                \"country\": country,\n                \"success\": False,\n            })\n            raise\n# Usage — logs produce JSONL like:\n# {\"timestamp\":\"2026-02-26T10:30:00Z\",\"url\":\"https:\u002F\u002F...\",\"status\":200,\"latency_ms\":1234,...}\nproxy_logger = JSONProxyLogger(\"proxy_requests.jsonl\")\nresponse = proxy_logger.fetch(\"https:\u002F\u002Fexample.com\u002Fdata\", country=\"us\")\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Ch2>定期保健报告\u003C\u002Fh2>\u003Cp>对于长期报废的刮刮机,编写定期的健康报告,总结固定窗口上的性能。\u003C\u002Fp>\u003Cpre>\u003Ccode>import time\nimport threading\nfrom datetime import datetime\nclass PeriodicReporter:\n    \"\"\"Generates periodic performance reports from proxy metrics.\"\"\"\n    def __init__(self, metrics: ProxyMetrics, interval_seconds: int = 60):\n        self.metrics = metrics\n        self.interval = interval_seconds\n        self._running = False\n        self._thread = None\n        self._last_snapshot = None\n    def start(self):\n        self._running = True\n        self._last_snapshot = self._snapshot()\n        self._thread = threading.Thread(target=self._report_loop, daemon=True)\n        self._thread.start()\n    def stop(self):\n        self._running = False\n    def _snapshot(self) -> dict:\n        return {\n            \"total\": self.metrics.total_requests,\n            \"success\": self.metrics.successful,\n            \"failed\": self.metrics.failed,\n            \"retries\": self.metrics.retries,\n            \"time\": time.time(),\n        }\n    def _report_loop(self):\n        while self._running:\n            time.sleep(self.interval)\n            current = self._snapshot()\n            prev = self._last_snapshot\n            elapsed = current[\"time\"] - prev[\"time\"]\n            requests_delta = current[\"total\"] - prev[\"total\"]\n            success_delta = current[\"success\"] - prev[\"success\"]\n            failed_delta = current[\"failed\"] - prev[\"failed\"]\n            rps = requests_delta \u002F elapsed if elapsed > 0 else 0\n            window_success_rate = (\n                (success_delta \u002F requests_delta * 100)\n                if requests_delta > 0 else 0\n            )\n            report = {\n                \"window\": f\"{self.interval}s\",\n                \"timestamp\": datetime.utcnow().isoformat(),\n                \"requests\": requests_delta,\n                \"rps\": round(rps, 1),\n                \"success_rate\": f\"{window_success_rate:.1f}%\",\n                \"failed\": failed_delta,\n                \"cumulative_success_rate\": f\"{self.metrics.success_rate:.1f}%\",\n                \"p95_latency\": f\"{self.metrics.p95_latency:.3f}s\",\n            }\n            print(f\"[REPORT] {report}\")\n            self._last_snapshot = current\n# Usage with MonitoredProxyClient\nclient = MonitoredProxyClient(max_retries=3)\nreporter = PeriodicReporter(client.metrics, interval_seconds=30)\nreporter.start()\n# Scrape away — reports print every 30 seconds\nfor url in urls:\n    client.fetch(url)\nreporter.stop()\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Ch2>警报规则和门槛\u003C\u002Fh2>\u003Cp>设置智能预警,避免在暖热期出现假阳性,瞬间发泡.\u003C\u002Fp>\u003Ctable>\n\u003Ccaption>警报规则和门槛\u003C\u002Fcaption>\u003Cthead>\u003Ctr>\u003Cth>警报\u003C\u002Fth>\u003Cth>条件\u003C\u002Fth>\u003Cth>冷却\u003C\u002Fth>\u003Cth>行动\u003C\u002Fth>\u003C\u002Ftr>\u003C\u002Fthead>\u003Ctbody>\u003Ctr>\u003Ctd>低成功率\u003C\u002Ftd>\u003Ctd>5分钟的窗口低于90%\u003C\u002Ftd>\u003Ctd>10分钟\u003C\u002Ftd>\u003Ctd>调查目标块, 检查代理池\u003C\u002Ftd>\u003C\u002Ftr>\u003Ctr>\u003Ctd>高纬度\u003C\u002Ftd>\u003Ctd>p95以上 2分钟窗口\u003C\u002Ftd>\u003Ctd>5分钟\u003C\u002Ftd>\u003Ctd>减少货币,检查目标健康\u003C\u002Ftd>\u003C\u002Ftr>\u003Ctr>\u003Ctd>错误 Spike\u003C\u002Ftd>\u003Ctd>单一错误类型超过请求的20%\u003C\u002Ftd>\u003Ctd>5分钟\u003C\u002Ftd>\u003Ctd>检查目标是否更改, 旋转地理位置\u003C\u002Ftd>\u003C\u002Ftr>\u003Ctr>\u003Ctd>带宽斯派克\u003C\u002Ftd>\u003Ctd>转移率比基线增加一倍\u003C\u002Ftd>\u003Ctd>15分钟\u003C\u002Ftd>\u003Ctd>校验预期行为, 检查方向循环\u003C\u002Ftd>\u003C\u002Ftr>\u003Ctr>\u003Ctd>零通量\u003C\u002Ftd>\u003Ctd>2分钟内无成功请求\u003C\u002Ftd>\u003Ctd>2分钟\u003C\u002Ftd>\u003Ctd>检查代理连接, 验证证书\u003C\u002Ftd>\u003C\u002Ftr>\u003C\u002Ftbody>\u003C\u002Ftable>\u003Cblockquote>良好的监测是连续数月可靠运行的刮刮管道与默默产生垃圾数据的刮刮管道的区别. 投资前置的仪器, 它支付自己 在第一次生产事件 你早期发现。\u003C\u002Fblockquote>\u003Cp>建一个中间器件供这些度量衡时参考 \u003Ca href=\"\u002Fcn\u002Fblog\u002Fdaili-zhongjian-jian-ceng\">构建代理软件中层\u003C\u002Fa>将 \" 在监测的同时优化吞吐量 \" 改为 \u003Ca href=\"\u002Fcn\u002Fblog\u002Fkuozhan-daili-qingqiu-bingfa-kongzhi\">以货币控制放大代理请求\u003C\u002Fa>。关于完整的系统设计,见 \u003Ca href=\"\u002Fcn\u002Fblog\u002Fsheji-kekaode-caiji-jiagou\">设计可靠的碎纸结构\u003C\u002Fa>。 。 。\u003C\u002Fp>\u003Cp>探索 \u003Ca href=\"https:\u002F\u002Fgithub.com\u002FProxyHatCom\u002Fpython-sdk\">Python SDK 键盘\u003C\u002Fa>, (中文). \u003Ca href=\"https:\u002F\u002Fgithub.com\u002FProxyHatCom\u002Fnode-sdk\">节点 SDK\u003C\u002Fa>,以及 \u003Ca href=\"https:\u002F\u002Fgithub.com\u002FProxyHatCom\u002Fgo-sdk\">冲啊 SDK\u003C\u002Fa> 用于代理集成,或检查 \u003Ca href=\"\u002Fcn\u002Fpricing\">代理用户定价\u003C\u002Fa> 和 \u003Ca href=\"https:\u002F\u002Fdocs.proxyhat.com\u002F\">文档\u003C\u002Fa> 开始吧\u003C\u002Fp>","监控和优化代理性能的完整指南。学习关键性能指标的测量方法、监控架构设计和自动告警系统搭建，确保代理系统稳定高效运行。","\u002Fcn\u002Fblog\u002Fjiankong-daili-xingneng",null,"https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fjiankong-daili-xingneng-og.webp",[16,19,22,25,28],{"question":17,"answer":18},"代理性能应该监控哪些关键指标？","关键指标包括：响应延迟（P50、P95、P99分位数）、请求成功率（按目标网站分类）、每秒请求数（吞吐量）、代理IP的可用率、带宽使用量、各HTTP状态码分布、CAPTCHA触发率和超时率。这些指标帮助您全面评估代理系统的健康状况。",{"question":20,"answer":21},"如何测量代理延迟？","记录每个请求的完整生命周期时间：从发出请求到收到完整响应。区分代理连接延迟（连接到代理服务器的时间）和端到端延迟（包括目标服务器响应时间）。使用分位数（P50、P95、P99）而非平均值来更准确地了解延迟分布。定期用标准测试URL进行基准测试。",{"question":23,"answer":24},"什么样的成功率算正常？","住宅代理在无保护网站上应达到98%以上成功率。在中度保护网站上90-95%。在高度保护网站（如Amazon、Google）上85-95%。数据中心代理在无保护网站上95%以上，在受保护网站上50-70%。如果成功率持续低于这些基准，说明代理质量或策略需要调整。",{"question":26,"answer":27},"如何设置代理性能告警？","设置以下告警阈值：成功率低于85%（严重）或90%（警告）、P95延迟超过5秒、CAPTCHA率超过10%、IP可用率低于80%。使用Prometheus + Alertmanager或类似工具实现自动告警。通过Slack、邮件或PagerDuty发送通知。设置告警升级策略避免告警疲劳。",{"question":29,"answer":30},"如何用监控数据优化代理策略？","分析成功率趋势：如果某目标的成功率持续下降，可能需要升级代理类型（如从数据中心切换到住宅）。分析延迟数据：延迟过高的代理IP自动降权或移除。分析失败模式：403比例高说明IP信誉问题，429比例高说明频率过高，超时比例高说明代理质量问题。",[32,33,34,35,36],"监控代理性能对于在数据管道受影响前捕获成功率下降和延迟上升等无声失败至关重要。","需要跟踪的关键指标包括成功率、延迟(p50\u002Fp95\u002Fp99)、错误率、每秒请求数和区块率。","文章提供了Python、Node.js和Go的生产就绪代码示例，用于检测代理客户端并收集指标。","建议使用结构化JSON日志记录每个代理请求，以便汇总和分析分布式抓取机的性能。","设置告警阈值（如成功率低于90%或p95延迟超过10秒）可将不可见问题转化为可操作的警报。",false,"2026-02-15T00:39:23+00:00","2026-07-19T03:13:07+00:00","2026-10-03T08:21:24+00:00","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fjiankong-daili-xingneng-master.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fjiankong-daili-xingneng-card.webp",11,{"name":45,"slug":46,"bio":47,"avatar_url":13,"website_url":13,"social_links":13},"ProxyHat Team","proxyhat-team","The ProxyHat editorial team covers proxies, web scraping, and data extraction.",[49],{"id":50,"slug":51,"name":52,"description":13,"meta_title":53,"meta_description":54,"parent_id":13},4,"kaifa-zhinan","开发者指南","开发者指南 | ProxyHat 博客","代码教程和SDK指南，帮助您将代理集成到应用程序中。",[56,60],{"id":57,"slug":58,"name":59},1,"web-scraping","网页抓取",{"id":61,"slug":62,"name":63},12,"sdk","SDK",{"it":65,"pt":66,"tr":67,"es":68,"pl":69,"de":70,"ru":71,"en":72,"fr":73,"zh":12,"ja":74,"ko":75,"x-default":72},"\u002Fit\u002Fblog\u002Fmonitoraggio-delle-prestazioni-del-proxy-latenza-il-tasso-di-successo-e-gli-avvisi","\u002Fpt\u002Fblog\u002Fmonitorando-desempenho-de-proxy","\u002Ftr\u002Fblog\u002Fproxy-performansini-izleme","\u002Fes\u002Fblog\u002Fmonitoreo-rendimiento-proxy","\u002Fpl\u002Fblog\u002Fmonitorowanie-wydajnosci-proxy-opoznienie-wskaznik-sukcesu-i-alerty","\u002Fde\u002Fblog\u002Fproxy-performance-ueberwachen","\u002Fru\u002Fblog\u002Fmonitoring-proizvoditelnosti-proksi","\u002Fblog\u002Fmonitoring-proxy-performance","\u002Ffr\u002Fblog\u002Fsurveiller-la-performance-des-proxies","\u002Fja\u002Fblog\u002Fprokishi-pafoomansu-no-kanshi","\u002Fko\u002Fblog\u002Fproxy-seongneung-monitoring",{"it":65,"pt":66,"tr":67,"es":68,"pl":69,"de":70,"ru":71,"en":72,"fr":73,"zh":12,"ja":74,"ko":75},77,[79,96,115,131],{"id":80,"slug":81,"title":82,"excerpt":83,"featured_image_url":84,"featured_image_alt":13,"card_image_url":85,"og_image_url":86,"published_at":87,"updated_at":39,"content_updated_at":88,"reading_time_minutes":61,"is_featured":37,"indexable":37,"views":89,"author":90,"categories":91,"tags":93},50,"sheji-kekaode-caiji-jiagou","设计可靠的网络爬虫架构","设计端到端的刮刮系统:排程器,URL队列,爬行器池,代理层,剖析器,存储,以及监控. 生产准备的 Python 代码与建筑图.","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fsheji-kekaode-caiji-jiagou-master.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fsheji-kekaode-caiji-jiagou-card.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fsheji-kekaode-caiji-jiagou-og.webp","2026-02-24T06:55:16+00:00","2026-10-03T08:21:25+00:00",73,{"name":45,"slug":46,"bio":47,"avatar_url":13,"website_url":13,"social_links":13},[92],{"id":50,"slug":51,"name":52,"description":13,"meta_title":53,"meta_description":54,"parent_id":13},[94,95],{"id":61,"slug":62,"name":63},{"id":57,"slug":58,"name":59},{"id":97,"slug":98,"title":99,"excerpt":100,"featured_image_url":101,"featured_image_alt":13,"card_image_url":102,"og_image_url":103,"published_at":104,"updated_at":39,"content_updated_at":105,"reading_time_minutes":106,"is_featured":37,"indexable":37,"views":80,"author":107,"categories":108,"tags":112},36,"kuozhan-caiji-jiagou","如何扩展网络爬虫基础设施","缩放网刮的架构模式:基于队列的系统,管道设计,带容器的横向缩放,以及规模化的代理管理. 代码在Python,Node.js,和去.","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fkuozhan-caiji-jiagou-master.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fkuozhan-caiji-jiagou-card.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fkuozhan-caiji-jiagou-og.webp","2026-02-09T14:42:34+00:00","2026-02-26T00:33:08+00:00",10,{"name":45,"slug":46,"bio":47,"avatar_url":13,"website_url":13,"social_links":13},[109],{"id":57,"slug":58,"name":59,"description":13,"meta_title":110,"meta_description":111,"parent_id":13},"网页抓取指南 | ProxyHat 博客","网页抓取技术、代理策略和数据提取最佳实践。",[113,114],{"id":57,"slug":58,"name":59},{"id":61,"slug":62,"name":63},{"id":116,"slug":117,"title":118,"excerpt":119,"featured_image_url":120,"featured_image_alt":13,"card_image_url":121,"og_image_url":122,"published_at":123,"updated_at":39,"content_updated_at":40,"reading_time_minutes":61,"is_featured":37,"indexable":37,"views":124,"author":125,"categories":126,"tags":128},35,"kuozhan-daili-qingqiu-bingfa-kongzhi","使用并发控制扩展代理请求","用于代理式刮刮的主货币图案:Ayncio semaphores,承诺池,Go工人池,限速器,以及反压. Python、Node.js和Go的生产代码.","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fkuozhan-daili-qingqiu-bingfa-kongzhi-master.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fkuozhan-daili-qingqiu-bingfa-kongzhi-card.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fkuozhan-daili-qingqiu-bingfa-kongzhi-og.webp","2026-02-08T11:16:13+00:00",362,{"name":45,"slug":46,"bio":47,"avatar_url":13,"website_url":13,"social_links":13},[127],{"id":50,"slug":51,"name":52,"description":13,"meta_title":53,"meta_description":54,"parent_id":13},[129,130],{"id":61,"slug":62,"name":63},{"id":57,"slug":58,"name":59},{"id":132,"slug":133,"title":134,"excerpt":135,"featured_image_url":136,"featured_image_alt":13,"card_image_url":137,"og_image_url":138,"published_at":139,"updated_at":39,"content_updated_at":140,"reading_time_minutes":61,"is_featured":37,"indexable":37,"views":141,"author":142,"categories":143,"tags":145},29,"daili-zhongjian-jian-ceng","构建爬虫代理中间件层","设计并构建生产级代理中件层,带有重试逻辑,故障,和度量衡. 在Python和Node.js中使用ProxyHat完成执行.","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fdaili-zhongjian-jian-ceng-master.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fdaili-zhongjian-jian-ceng-card.webp","https:\u002F\u002Fstatic.proxyhat.com\u002Fstorage\u002Fblog\u002Fdaili-zhongjian-jian-ceng-og.webp","2026-02-02T07:15:32+00:00","2026-10-03T08:21:32+00:00",45,{"name":45,"slug":46,"bio":47,"avatar_url":13,"website_url":13,"social_links":13},[144],{"id":50,"slug":51,"name":52,"description":13,"meta_title":53,"meta_description":54,"parent_id":13},[146,147],{"id":61,"slug":62,"name":63},{"id":57,"slug":58,"name":59},[]]