or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cache-monitoring.mddatabase-monitoring.mdhttp-monitoring.mdindex.mdmetrics-export.mdmigration-monitoring.mdmodel-monitoring.mdtesting-utilities.md

index.mddocs/

0

# Django Prometheus

1

2

Django middlewares to monitor your application with Prometheus.io. Provides comprehensive monitoring capabilities for Django applications through middleware components that automatically collect and export metrics for HTTP requests/responses, database operations, cache access, and model operations.

3

4

## Package Information

5

6

- **Package Name**: django-prometheus

7

- **Language**: Python

8

- **Installation**: `pip install django-prometheus`

9

- **Django Version Support**: 4.2, 5.0, 5.1, 5.2

10

- **Python Version Support**: 3.9, 3.10, 3.11, 3.12, 3.13

11

12

## Core Imports

13

14

```python

15

import django_prometheus

16

```

17

18

Common imports for middleware:

19

20

```python

21

from django_prometheus.middleware import PrometheusBeforeMiddleware, PrometheusAfterMiddleware

22

```

23

24

For model monitoring:

25

26

```python

27

from django_prometheus.models import ExportModelOperationsMixin

28

```

29

30

For exporting metrics:

31

32

```python

33

from django_prometheus.exports import ExportToDjangoView, SetupPrometheusEndpointOnPort, SetupPrometheusEndpointOnPortRange, SetupPrometheusExportsFromConfig

34

```

35

36

For testing utilities:

37

38

```python

39

from django_prometheus.testutils import assert_metric_equal, save_registry, assert_metric_diff, get_metric

40

```

41

42

For migration monitoring:

43

44

```python

45

from django_prometheus.migrations import ExportMigrations, ExportMigrationsForDatabase

46

```

47

48

For utility classes:

49

50

```python

51

from django_prometheus.utils import PowersOf, Time, TimeSince

52

```

53

54

For app configuration:

55

56

```python

57

from django_prometheus.apps import DjangoPrometheusConfig

58

```

59

60

## Basic Usage

61

62

### Configuration

63

64

Add to Django settings:

65

66

```python

67

# settings.py

68

69

INSTALLED_APPS = [

70

'django_prometheus',

71

# ... other apps

72

]

73

74

MIDDLEWARE = [

75

'django_prometheus.middleware.PrometheusBeforeMiddleware',

76

# ... other middleware

77

'django_prometheus.middleware.PrometheusAfterMiddleware',

78

]

79

80

# Optional: Export metrics on a separate port

81

PROMETHEUS_METRICS_EXPORT_PORT = 8001

82

PROMETHEUS_METRICS_EXPORT_PORT_RANGE = range(8001, 8005)

83

PROMETHEUS_METRICS_EXPORT_ADDRESS = ""

84

85

# Optional: Custom metric namespace (prefixes all metrics)

86

PROMETHEUS_METRIC_NAMESPACE = "myproject"

87

88

# Optional: Custom histogram latency buckets

89

PROMETHEUS_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"))

90

91

# Optional: Disable migration monitoring

92

PROMETHEUS_EXPORT_MIGRATIONS = False

93

```

94

95

Add metrics URL to your project:

96

97

```python

98

# urls.py

99

from django.urls import path, include

100

101

urlpatterns = [

102

path('', include('django_prometheus.urls')),

103

# ... other patterns

104

]

105

```

106

107

### Model Monitoring

108

109

```python

110

from django.db import models

111

from django_prometheus.models import ExportModelOperationsMixin

112

113

class User(ExportModelOperationsMixin('user'), models.Model):

114

username = models.CharField(max_length=100)

115

email = models.EmailField()

116

```

117

118

## Capabilities

119

120

### HTTP Monitoring Middleware

121

122

Comprehensive monitoring of HTTP requests, responses, exceptions, and latencies through Django middleware. Tracks method, status codes, view names, response sizes, and more.

123

124

```python { .api }

125

class PrometheusBeforeMiddleware:

126

def process_request(self, request): ...

127

def process_response(self, request, response): ...

128

129

class PrometheusAfterMiddleware:

130

def process_request(self, request): ...

131

def process_view(self, request, view_func, *view_args, **view_kwargs): ...

132

def process_template_response(self, request, response): ...

133

def process_response(self, request, response): ...

134

def process_exception(self, request, exception): ...

135

```

136

137

[HTTP Monitoring](./http-monitoring.md)

138

139

### Model Operation Tracking

140

141

Monitor Django model operations (insert, update, delete) by model name through mixin classes that instrument Django ORM operations.

142

143

```python { .api }

144

def ExportModelOperationsMixin(model_name: str):

145

"""

146

Returns a mixin class for models to export counters for lifecycle operations.

147

148

Parameters:

149

- model_name: str, name of the model for metric labeling

150

151

Returns:

152

Mixin class with instrumented _do_insert, _do_update, delete methods

153

"""

154

```

155

156

[Model Monitoring](./model-monitoring.md)

157

158

### Database Backend Monitoring

159

160

Automatic monitoring of database operations through instrumented Django database backends. Tracks connection counts, query execution times, errors, and bulk operations.

161

162

```python { .api }

163

# Database backends with monitoring

164

django_prometheus.db.backends.postgresql.base.DatabaseWrapper

165

django_prometheus.db.backends.mysql.base.DatabaseWrapper

166

django_prometheus.db.backends.sqlite3.base.DatabaseWrapper

167

django_prometheus.db.backends.spatialite.base.DatabaseWrapper

168

django_prometheus.db.backends.postgis.base.DatabaseWrapper

169

```

170

171

[Database Monitoring](./database-monitoring.md)

172

173

### Cache Backend Monitoring

174

175

Monitor Django cache operations (get/hit/miss/fail) through instrumented cache backends for various cache systems.

176

177

```python { .api }

178

# Cache backends with monitoring

179

django_prometheus.cache.backends.filebased.FileBasedCache

180

django_prometheus.cache.backends.locmem.LocMemCache

181

django_prometheus.cache.backends.memcached.PyMemcacheCache

182

django_prometheus.cache.backends.redis.RedisCache

183

```

184

185

[Cache Monitoring](./cache-monitoring.md)

186

187

### Metrics Export

188

189

Export Prometheus metrics through Django views or standalone HTTP servers, with support for multiprocess environments.

190

191

```python { .api }

192

def ExportToDjangoView(request):

193

"""

194

Exports /metrics as a Django view.

195

196

Parameters:

197

- request: Django HttpRequest object

198

199

Returns:

200

HttpResponse with Prometheus metrics data

201

"""

202

203

def SetupPrometheusEndpointOnPort(port: int, addr: str = ""):

204

"""

205

Exports Prometheus metrics on HTTPServer running in its own thread.

206

207

Parameters:

208

- port: int, port number to serve metrics on

209

- addr: str, address to bind to (default: all interfaces)

210

"""

211

212

def SetupPrometheusEndpointOnPortRange(port_range, addr: str = ""):

213

"""

214

Like SetupPrometheusEndpointOnPort, but tries several ports.

215

216

Parameters:

217

- port_range: iterable of ports to try

218

- addr: str, address to bind to (default: all interfaces)

219

220

Returns:

221

int: chosen port, or None if no port available

222

"""

223

224

def SetupPrometheusExportsFromConfig():

225

"""

226

Exports metrics based on Django settings configuration.

227

Reads PROMETHEUS_METRICS_EXPORT_* settings and starts appropriate server.

228

"""

229

```

230

231

[Metrics Export](./metrics-export.md)

232

233

### Migration Monitoring

234

235

Track applied and unapplied Django migrations across database connections to monitor deployment and migration status.

236

237

```python { .api }

238

def ExportMigrations():

239

"""

240

Exports counts of unapplied migrations.

241

Called during app startup via AppConfig.ready().

242

"""

243

244

def ExportMigrationsForDatabase(alias: str, executor):

245

"""

246

Exports migration counts for specific database.

247

248

Parameters:

249

- alias: str, database connection alias

250

- executor: Django MigrationExecutor instance

251

"""

252

```

253

254

[Migration Monitoring](./migration-monitoring.md)

255

256

### Utility Functions

257

258

Helper functions for time measurement and histogram bucket generation used internally by monitoring components.

259

260

```python { .api }

261

def Time():

262

"""

263

Returns high-resolution timestamp representation for latency measurement.

264

265

Returns:

266

Opaque time object (should only be used with TimeSince)

267

"""

268

269

def TimeSince(t):

270

"""

271

Computes time elapsed since a timestamp from Time().

272

273

Parameters:

274

- t: Time object returned by Time()

275

276

Returns:

277

float: Elapsed time in fractional seconds

278

"""

279

280

def PowersOf(logbase: int, count: int, lower: int = 0, include_zero: bool = True):

281

"""

282

Generates histogram buckets as powers of a base number.

283

284

Parameters:

285

- logbase: int, base for power calculation

286

- count: int, number of powers to generate

287

- lower: int, starting power (default: 0)

288

- include_zero: bool, whether to include 0 as first bucket

289

290

Returns:

291

list: Bucket boundaries for histogram metrics

292

"""

293

```

294

295

### Application Configuration

296

297

Django app configuration that automatically initializes metrics exports and migration monitoring on startup.

298

299

```python { .api }

300

class DjangoPrometheusConfig(AppConfig):

301

"""

302

Django app configuration for django-prometheus.

303

Handles automatic initialization of metrics exports and migration monitoring.

304

"""

305

306

name = "django_prometheus"

307

verbose_name = "Django-Prometheus"

308

309

def ready(self):

310

"""

311

Initializes Prometheus exports and migration monitoring on Django startup.

312

Called automatically when Django loads the app, including for management commands.

313

"""

314

```

315

316

### Testing Utilities

317

318

Comprehensive test utilities for asserting Prometheus metric values and changes in test suites.

319

320

```python { .api }

321

def assert_metric_equal(expected_value, metric_name: str, registry=REGISTRY, **labels):

322

"""

323

Asserts that metric equals expected value.

324

325

Parameters:

326

- expected_value: expected metric value

327

- metric_name: str, name of the metric

328

- registry: Prometheus registry (default: REGISTRY)

329

- **labels: metric label filters

330

"""

331

332

def save_registry(registry=REGISTRY):

333

"""

334

Freezes current state of metrics registry for comparison.

335

336

Parameters:

337

- registry: Prometheus registry to freeze

338

339

Returns:

340

Frozen registry state for later comparison

341

"""

342

343

def assert_metric_diff(frozen_registry, expected_diff, metric_name: str, registry=REGISTRY, **labels):

344

"""

345

Asserts that metric changed by expected_diff between frozen registry and now.

346

347

Parameters:

348

- frozen_registry: Previously frozen registry state

349

- expected_diff: Expected change in metric value

350

- metric_name: str, name of the metric

351

- registry: Prometheus registry (default: REGISTRY)

352

- **labels: metric label filters

353

"""

354

355

def get_metric(metric_name: str, registry=REGISTRY, **labels):

356

"""

357

Gets a single metric value.

358

359

Parameters:

360

- metric_name: str, name of the metric

361

- registry: Prometheus registry (default: REGISTRY)

362

- **labels: metric label filters

363

364

Returns:

365

Metric value or None if not found

366

"""

367

```

368

369

[Testing Utilities](./testing-utilities.md)

370

371

## Types

372

373

```python { .api }

374

from prometheus_client import Counter, Histogram, Gauge

375

from django.http import HttpRequest, HttpResponse

376

from django.utils.deprecation import MiddlewareMixin

377

from django.db.migrations.executor import MigrationExecutor

378

```