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

如何使用Prometheus统计Django服务器单日发送邮件总量?(指定依赖版本)

How to Track Daily Email Volume from Django Server with Prometheus (django-prometheus 2.1.0, prometheus-client 0.8.0, Django 2.2.17)

Absolutely! You can definitely track the total number of emails sent by your Django server in a day using your specified stack. Here's a practical, step-by-step implementation:

1. Create a Wrapper for Django's Email Sending Functions

Since django-prometheus 2.1.0 doesn't include built-in metrics for email sending, we'll use prometheus-client to add a counter that tracks every email sent.

Create a utility file (e.g., utils/email_metrics.py) in your Django project:

from prometheus_client import Counter
from django.core.mail import send_mail as django_send_mail
from django.core.mail import send_mass_mail as django_send_mass_mail

# Define a counter with a label for tracking send status (success/failed/error)
email_sent_total = Counter(
    'django_email_sent_total',
    'Total number of emails sent by Django application',
    ['status']
)

def send_mail(*args, **kwargs):
    """Wrapper around Django's send_mail to track metrics"""
    try:
        sent_count = django_send_mail(*args, **kwargs)
        if sent_count > 0:
            email_sent_total.labels(status='success').inc()
        else:
            email_sent_total.labels(status='failed').inc()
        return sent_count
    except Exception:
        email_sent_total.labels(status='error').inc()
        raise

def send_mass_mail(datatuple, fail_silently=False, auth_user=None, auth_password=None, connection=None):
    """Wrapper around Django's send_mass_mail to track metrics"""
    try:
        sent_count = django_send_mass_mail(datatuple, fail_silently, auth_user, auth_password, connection)
        if sent_count > 0:
            # Increment by the number of successfully sent emails
            email_sent_total.labels(status='success').inc(sent_count)
        else:
            email_sent_total.labels(status='failed').inc()
        return sent_count
    except Exception:
        email_sent_total.labels(status='error').inc()
        raise

2. Replace Default Email Functions in Your Project

Update all places in your code where you use send_mail or send_mass_mail to import and use your wrapped versions instead:

from utils.email_metrics import send_mail, send_mass_mail

# Example usage
send_mail(
    'Subject here',
    'Here is the message.',
    'from@example.com',
    ['to@example.com'],
    fail_silently=False,
)

If you're using Django's EmailMessage class directly, you'll need to wrap its send() method similarly.

3. Ensure Django-Prometheus is Configured Correctly

Double-check that django-prometheus is set up to expose metrics:

Update settings.py:

INSTALLED_APPS = [
    # ... your other apps
    'django_prometheus',
]

MIDDLEWARE = [
    'django_prometheus.middleware.PrometheusBeforeMiddleware',
    # ... your existing middleware
    'django_prometheus.middleware.PrometheusAfterMiddleware',
]

Update urls.py:

from django.urls import path, include

urlpatterns = [
    # ... your other URL patterns
    path('metrics/', include('django_prometheus.urls')),
]

Start your Django server, then visit http://your-server-url/metrics — you should see the django_email_sent_total metric listed once emails are sent.

4. Configure Prometheus to Scrape Your Django App

Add a scrape job to your Prometheus configuration file (prometheus.yml):

scrape_configs:
  - job_name: 'django_email_tracker'
    static_configs:
      - targets: ['your-django-server-ip:port']  # e.g., 'localhost:8000'
    scrape_interval: 15s  # Adjust based on your needs

Restart Prometheus to apply the changes.

5. Query Daily Email Volume with PromQL

Once metrics are being collected, use these PromQL queries in the Prometheus UI or Grafana:

  • Total emails sent in the last 24 hours:

    sum(increase(django_email_sent_total[1d]))
    
  • Successful emails sent in the last 24 hours:

    sum(increase(django_email_sent_total{status="success"}[1d]))
    
  • Failed/error emails in the last 24 hours:

    sum(increase(django_email_sent_total{status=~"failed|error"}[1d]))
    

Notes for Your Stack Version

  • prometheus-client 0.8.0 supports the Counter and labels syntax used here.
  • django-prometheus 2.1.0 works seamlessly with Django 2.2.17 for exposing metrics endpoints.
  • If you use Celery for async email sending, make sure your wrapped email functions are used in Celery tasks to track those emails too.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:24:18