You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何监控Heroku部署的ReactJS+Django应用的请求路由与成本?

Monitoring High-Frequency Request Routes/URLs & Tracking Heroku Costs

Great question! Let's break this down into two clear parts: monitoring your high-traffic API routes/URLs, and tracking monthly costs on Heroku. I’ve built and maintained React+Django apps hosted on Heroku, so here’s practical, actionable advice:

Part 1: Monitoring High-Frequency Requests

You’ve got a few solid options here, spanning backend, frontend, and Heroku-native tools.

1. Django Backend: Custom Middleware (Most Reliable)

Since your backend handles all incoming requests, adding a custom middleware to log request details is the most straightforward way to track which URLs are getting hit the most.

Here’s a simple middleware you can drop into your app:

# myapp/middleware/request_tracker.py
import time
import logging
from django.utils.deprecation import MiddlewareMixin

logger = logging.getLogger("request_tracker")

class RequestTrackingMiddleware(MiddlewareMixin):
    def process_request(self, request):
        # Record start time to calculate request duration
        request._start_time = time.time()

    def process_response(self, request, response):
        if hasattr(request, "_start_time"):
            duration = round(time.time() - request._start_time, 3)
            # Log key details: path, method, status, duration, client IP
            log_msg = (
                f"PATH: {request.path} | METHOD: {request.method} | "
                f"STATUS: {response.status_code} | DURATION: {duration}s | "
                f"CLIENT: {request.META.get('REMOTE_ADDR', 'unknown')}"
            )
            logger.info(log_msg)
        return response

Register it in your settings.py:

MIDDLEWARE = [
    # ... other middleware (place it near the top for full coverage)
    "myapp.middleware.request_tracker.RequestTrackingMiddleware",
]

Then configure Django’s logging to output these logs to Heroku’s Logplex (Heroku automatically captures Django logs by default). Later, you can analyze these logs to spot high-frequency URLs.

2. Frontend: Axios Interceptors

For frontend-side tracking (to catch client-side request details), add Axios interceptors to log and report request stats to your backend. This is useful if you want to track frontend-specific behavior (like failed requests that never reach your backend).

Example Axios setup:

// src/api/axios.js
import axios from "axios";

// Request interceptor: track start time
axios.interceptors.request.use(
  (config) => {
    config.metadata = { startTime: new Date() };
    return config;
  },
  (error) => Promise.reject(error)
);

// Response interceptor: calculate duration and report to backend
axios.interceptors.response.use(
  (response) => {
    response.config.metadata.endTime = new Date();
    const duration = response.config.metadata.endTime - response.config.metadata.startTime;
    
    // Send stats to a dedicated Django endpoint (create this first!)
    axios.post("/api/request-stats", {
      url: response.config.url,
      method: response.config.method,
      duration,
      status: response.status,
    }).catch(err => console.error("Failed to report request stats:", err));
    
    return response;
  },
  (error) => {
    if (error.config) {
      error.config.metadata.endTime = new Date();
      const duration = error.config.metadata.endTime - error.config.metadata.startTime;
      
      axios.post("/api/request-stats", {
        url: error.config.url,
        method: error.config.method,
        duration,
        status: error.response?.status || "client_error",
      }).catch(err => console.error("Failed to report error stats:", err));
    }
    return Promise.reject(error);
  }
);

export default axios;

On the Django side, create a RequestStat model to store these stats, then build a simple admin view or dashboard to sort URLs by request count.

3. Heroku-Native Tools

Heroku has built-in and plugin-based tools to analyze your logs:

  • Heroku Logs CLI: Run heroku logs --tail to stream logs in real-time, or use heroku logs --search "/api/" to filter API requests.
  • Log Analysis Plugins: Install plugins like Papertrail or SolarWinds Loggly from the Heroku Marketplace. These tools let you search, filter, and create charts to visualize request frequency per URL.
  • New Relic: The Heroku New Relic plugin gives you full application performance monitoring (APM), including breakdowns of request volume and latency per route. It’s a bit more heavyweight but perfect for production apps.

Part 2: Heroku Cost Tracking & Request-Cost Correlation

Heroku’s costs come from dynos, databases, add-ons, and bandwidth. Here’s how to track them, and link them to your request volume:

1. Monthly Cost Breakdown

  • Heroku Billing Dashboard: Go to your Heroku Account → Billing to see a detailed breakdown of monthly charges. It splits costs by dyno hours, database usage, add-ons, and bandwidth.
  • Heroku CLI: Use heroku billing:charges to view past invoices, or heroku billing:usage to check current-cycle usage (e.g., how many dyno hours you’ve used so far).

2. Linking Requests to Costs

While Heroku doesn’t directly tie individual requests to costs, you can correlate your request data with cost drivers:

  • Dyno Costs: Higher request volume may require more dyno hours or larger dyno sizes. Use Heroku Metrics (App → Metrics) to view request rate alongside dyno usage, and cross-reference with your billing data.
  • Bandwidth Costs: Outbound bandwidth is charged at $0.01/GB. Heroku Metrics shows outbound traffic, so you can compare this to your high-frequency request routes (e.g., a route serving large files will drive more bandwidth costs).
  • Database Costs: If your high-frequency requests hit the database heavily, you might see higher database usage (e.g., connection limits, storage). Use your database’s built-in monitoring (like PostgreSQL’s pg_stat_statements) alongside Heroku’s database metrics.

3. Cost Optimization Tips

  • Use Heroku’s Autoscaling for dynos to match request volume, so you don’t pay for unused capacity.
  • Cache frequent requests (e.g., with Django’s cache_page decorator) to reduce dyno and database load.
  • Review add-on usage: some monitoring/logging add-ons have tiered pricing, so make sure you’re on a plan that fits your needs.

内容的提问来源于stack exchange,提问作者rhemon19

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:48:33