{"id":13468631,"url":"https://github.com/korfuri/django-prometheus","last_synced_at":"2025-05-11T03:51:41.901Z","repository":{"id":29887653,"uuid":"33433092","full_name":"korfuri/django-prometheus","owner":"korfuri","description":"Export Django monitoring metrics for Prometheus.io","archived":false,"fork":false,"pushed_at":"2024-12-09T22:17:04.000Z","size":589,"stargazers_count":1549,"open_issues_count":87,"forks_count":248,"subscribers_count":25,"default_branch":"master","last_synced_at":"2025-05-11T03:51:35.211Z","etag":null,"topics":["django","django-prometheus","exported-metrics","metrics","monitoring","prometheus","prometheus-client","python"],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/korfuri.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2015-04-05T06:53:05.000Z","updated_at":"2025-05-10T02:57:08.000Z","dependencies_parsed_at":"2025-01-07T01:18:00.528Z","dependency_job_id":"1435c3d1-cb04-429a-ad40-1ec857df674a","html_url":"https://github.com/korfuri/django-prometheus","commit_stats":{"total_commits":423,"total_committers":58,"mean_commits":7.293103448275862,"dds":0.5981087470449172,"last_synced_commit":"6a50dc8c025ef39edee67afd30305cb8b8eb1117"},"previous_names":[],"tags_count":32,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/korfuri%2Fdjango-prometheus","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/korfuri%2Fdjango-prometheus/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/korfuri%2Fdjango-prometheus/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/korfuri%2Fdjango-prometheus/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/korfuri","download_url":"https://codeload.github.com/korfuri/django-prometheus/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253514569,"owners_count":21920335,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["django","django-prometheus","exported-metrics","metrics","monitoring","prometheus","prometheus-client","python"],"created_at":"2024-07-31T15:01:15.377Z","updated_at":"2025-05-11T03:51:41.882Z","avatar_url":"https://github.com/korfuri.png","language":"Python","funding_links":[],"categories":["Python","Monitoring","Third-Party Packages"],"sub_categories":["Tools","Monitoring"],"readme":"# django-prometheus\n\nExport Django monitoring metrics for Prometheus.io\n\n[![Join the chat at https://gitter.im/django-prometheus/community](https://badges.gitter.im/django-prometheus/community.svg)](https://gitter.im/django-prometheus/community?utm_source=badge\u0026utm_medium=badge\u0026utm_campaign=pr-badge\u0026utm_content=badge)\n\n[![PyPI version](https://badge.fury.io/py/django-prometheus.svg)](http://badge.fury.io/py/django-prometheus)\n[![Build Status](https://github.com/korfuri/django-prometheus/actions/workflows/ci.yml/badge.svg)](https://github.com/korfuri/django-prometheus/actions/workflows/ci.yml)\n[![Coverage Status](https://coveralls.io/repos/github/korfuri/django-prometheus/badge.svg?branch=master)](https://coveralls.io/github/korfuri/django-prometheus?branch=master)\n[![PyPi page link -- Python versions](https://img.shields.io/pypi/pyversions/django-prometheus.svg)](https://pypi.python.org/pypi/django-prometheus)\n\n\n## Features\n\nThis library provides Prometheus metrics for Django related operations:\n\n* Requests \u0026 Responses\n* Database access done via [Django ORM](https://docs.djangoproject.com/en/3.2/topics/db/)\n* Cache access done via [Django Cache framework](https://docs.djangoproject.com/en/3.2/topics/cache/)\n\n## Usage\n\n### Requirements\n\n* Django \u003e= 4.2\n* Python 3.8 and above.\n\n### Installation\n\nInstall with:\n\n```shell\npip install django-prometheus\n```\n\nOr, if you're using a development version cloned from this repository:\n\n```shell\npython path-to-where-you-cloned-django-prometheus/setup.py install\n```\n\nThis will install [prometheus_client](https://github.com/prometheus/client_python) as a dependency.\n\n### Quickstart\n\nIn your settings.py:\n\n```python\nINSTALLED_APPS = [\n   ...\n   'django_prometheus',\n   ...\n]\n\nMIDDLEWARE = [\n    'django_prometheus.middleware.PrometheusBeforeMiddleware',\n    # All your other middlewares go here, including the default\n    # middlewares like SessionMiddleware, CommonMiddleware,\n    # CsrfViewmiddleware, SecurityMiddleware, etc.\n    'django_prometheus.middleware.PrometheusAfterMiddleware',\n]\n```\n\nIn your urls.py:\n\n```python\nurlpatterns = [\n    ...\n    path('', include('django_prometheus.urls')),\n]\n```\n\n### Configuration\n\nPrometheus uses Histogram based grouping for monitoring latencies. The default\nbuckets are:\n\n```python\nPROMETHEUS_LATENCY_BUCKETS = (0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1.0, 2.5, 5.0, 7.5, 10.0, 25.0, 50.0, 75.0, float(\"inf\"),)\n```\n\nYou can define custom buckets for latency, adding more buckets decreases performance but\nincreases accuracy: \u003chttps://prometheus.io/docs/practices/histograms/\u003e\n\n```python\nPROMETHEUS_LATENCY_BUCKETS = (.1, .2, .5, .6, .8, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.5, 9.0, 12.0, 15.0, 20.0, 30.0, float(\"inf\"))\n```\n\n---\n\nYou can have a custom namespace for your metrics:\n\n```python\nPROMETHEUS_METRIC_NAMESPACE = \"project\"\n```\n\nThis will prefix all metrics with `project_` word like this:\n\n```text\nproject_django_http_requests_total_by_method_total{method=\"GET\"} 1.0\n```\n\n### Monitoring your databases\n\nSQLite, MySQL, and PostgreSQL databases can be monitored. Just\nreplace the `ENGINE` property of your database, replacing\n`django.db.backends` with `django_prometheus.db.backends`.\n\n```python\nDATABASES = {\n    'default': {\n        'ENGINE': 'django_prometheus.db.backends.sqlite3',\n        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n    },\n}\n```\n\n### Monitoring your caches\n\nFilebased, memcached, redis caches can be monitored. Just replace\nthe cache backend to use the one provided by django_prometheus\n`django.core.cache.backends` with `django_prometheus.cache.backends`.\n\n```python\nCACHES = {\n    'default': {\n        'BACKEND': 'django_prometheus.cache.backends.filebased.FileBasedCache',\n        'LOCATION': '/var/tmp/django_cache',\n    }\n}\n```\n\n### Monitoring your models\n\nYou may want to monitor the creation/deletion/update rate for your\nmodel. This can be done by adding a mixin to them. This is safe to do\non existing models (it does not require a migration).\n\nIf your model is:\n\n```python\nclass Dog(models.Model):\n    name = models.CharField(max_length=100, unique=True)\n    breed = models.CharField(max_length=100, blank=True, null=True)\n    age = models.PositiveIntegerField(blank=True, null=True)\n```\n\nJust add the `ExportModelOperationsMixin` as such:\n\n```python\nfrom django_prometheus.models import ExportModelOperationsMixin\n\nclass Dog(ExportModelOperationsMixin('dog'), models.Model):\n    name = models.CharField(max_length=100, unique=True)\n    breed = models.CharField(max_length=100, blank=True, null=True)\n    age = models.PositiveIntegerField(blank=True, null=True)\n```\n\nThis will export 3 metrics, `django_model_inserts_total{model=\"dog\"}`,\n`django_model_updates_total{model=\"dog\"}` and\n`django_model_deletes_total{model=\"dog\"}`.\n\nNote that the exported metrics are counters of creations,\nmodifications and deletions done in the current process. They are not\ngauges of the number of objects in the model.\n\nStarting with Django 1.7, migrations are also monitored. Two gauges\nare exported, `django_migrations_applied_by_connection` and\n`django_migrations_unapplied_by_connection`. You may want to alert if\nthere are unapplied migrations.\n\nIf you want to disable the Django migration metrics, set the\n`PROMETHEUS_EXPORT_MIGRATIONS` setting to False.\n\n### Monitoring and aggregating the metrics\n\nPrometheus is quite easy to set up. An example prometheus.conf to\nscrape `127.0.0.1:8001` can be found in `examples/prometheus`.\n\nHere's an example of a PromDash displaying some of the metrics\ncollected by django-prometheus:\n\n![Example dashboard](https://raw.githubusercontent.com/korfuri/django-prometheus/master/examples/django-promdash.png)\n\n## Adding your own metrics\n\nYou can add application-level metrics in your code by using\n[prometheus_client](https://github.com/prometheus/client_python)\ndirectly. The exporter is global and will pick up your metrics.\n\nTo add metrics to the Django internals, the easiest way is to extend\ndjango-prometheus' classes. Please consider contributing your metrics,\npull requests are welcome. Make sure to read the Prometheus best\npractices on\n[instrumentation](http://prometheus.io/docs/practices/instrumentation/)\nand [naming](http://prometheus.io/docs/practices/naming/).\n\n## Importing Django Prometheus using only local settings\n\nIf you wish to use Django Prometheus but are not able to change\nthe code base, it's possible to have all the default metrics by\nmodifying only the settings.\n\nFirst step is to inject prometheus' middlewares and to add\ndjango_prometheus in INSTALLED_APPS\n\n```python\nMIDDLEWARE = \\\n    ['django_prometheus.middleware.PrometheusBeforeMiddleware'] + \\\n    MIDDLEWARE + \\\n    ['django_prometheus.middleware.PrometheusAfterMiddleware']\n\nINSTALLED_APPS += ['django_prometheus']\n```\n\nSecond step is to create the /metrics end point, for that we need\nanother file (called urls_prometheus_wrapper.py in this example) that\nwill wraps the apps URLs and add one on top:\n\n```python\nfrom django.urls import include, path\n\n\nurlpatterns = []\n\nurlpatterns.append(path('prometheus/', include('django_prometheus.urls')))\nurlpatterns.append(path('', include('myapp.urls')))\n```\n\nThis file will add a \"/prometheus/metrics\" end point to the URLs of django\nthat will export the metrics (replace myapp by your project name).\n\nThen we inject the wrapper in settings:\n\n```python\nROOT_URLCONF = \"graphite.urls_prometheus_wrapper\"\n```\n\n## Adding custom labels to middleware (request/response) metrics\n\nYou can add application specific labels to metrics reported by the django-prometheus middleware.\nThis involves extending the classes defined in middleware.py.\n\n* Extend the Metrics class and override the `register_metric` method to add the application specific labels.\n* Extend middleware classes, set the metrics_cls class attribute to the the extended metric class and override the label_metric method to attach custom metrics.\n\nSee implementation example in [the test app](django_prometheus/tests/end2end/testapp/test_middleware_custom_labels.py#L19-L46)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkorfuri%2Fdjango-prometheus","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkorfuri%2Fdjango-prometheus","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkorfuri%2Fdjango-prometheus/lists"}