Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

feat: Add instrumentation for psycopg3 (#983)

Ishan Jain18924bbac67c
diff --git a/docs/latest/sdk/configuration.mdx b/docs/latest/sdk/configuration.mdx
index 4f3dceab..af47266c 100644
--- a/docs/latest/sdk/configuration.mdx
+++ b/docs/latest/sdk/configuration.mdx
@@ -50,6 +50,33 @@ Customize OpenLIT SDK behavior for your specific instrumentation needs:
| `event_logger` | N/A | N/A | EventLoggerProvider instance | `None` | No |
| `meter` | N/A | N/A | OpenTelemetry Metrics instance | `None` | No |
+### Database instrumentation options
+
+These options apply to database instrumentations like PostgreSQL (psycopg3):
+
+| Parameter | CLI Argument | Environment Variable | Description | Default | Required |
+|-----------|--------------|---------------------|-------------|---------|----------|
+| `capture_parameters` | `--capture_parameters` | `OPENLIT_CAPTURE_PARAMETERS` | Capture database query parameters in spans (security risk - may expose sensitive data) | `False` | No |
+| `enable_sqlcommenter` | `--enable_sqlcommenter` | `OPENLIT_ENABLE_SQLCOMMENTER` | Inject OpenTelemetry trace context as SQL comments for database log correlation | `False` | No |
+
+<Warning>
+**Security Notice**: Enabling `capture_parameters` records query parameters (the values passed to `$1`, `$2`, etc.) in your traces. This may expose sensitive data like passwords, API keys, or personal information. Only enable in development environments or when you're certain parameters don't contain sensitive data.
+</Warning>
+
+**SQLCommenter Example:**
+
+When `enable_sqlcommenter` is enabled, queries are automatically modified to include trace context:
+
+```sql
+-- Original
+SELECT * FROM users WHERE id = $1;
+
+-- With SQLCommenter
+SELECT * FROM users WHERE id = $1 /*traceparent='00-abc123def456-789xyz-01',application='my_app'*/;
+```
+
+This enables correlation between application traces and database logs (e.g., `pg_stat_statements`, `auto_explain`).
+
### Deprecated parameters
| Parameter | CLI Argument | Environment Variable | Description | Default | Required |
diff --git a/docs/latest/sdk/integrations/overview.mdx b/docs/latest/sdk/integrations/overview.mdx
index 716576e5..b087339f 100644
--- a/docs/latest/sdk/integrations/overview.mdx
+++ b/docs/latest/sdk/integrations/overview.mdx
@@ -2087,6 +2087,26 @@ Start integrating and monitoring your applications with OpenLIT in just one line
</Card>
</CardGroup>
+### Databases
+<CardGroup cols={2}>
+ <Card
+ title="PostgreSQL (psycopg3)"
+ href="/latest/sdk/integrations/psycopg"
+ icon={
+ <svg viewBox="0 0 256 264" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid">
+ <title>PostgreSQL</title>
+ <path d="M255.008 158.086c-1.535-4.649-5.556-7.887-10.756-8.664-2.452-.366-5.26-.21-8.583.475-5.792 1.195-10.089 1.65-13.225 1.738 11.837-19.985 21.462-42.775 27.003-64.228 8.96-34.689 4.172-50.492-1.423-57.64C233.217 10.847 211.614.683 185.552.372c-13.903-.17-26.108 2.575-32.475 4.549-5.928-1.046-12.302-1.63-18.99-1.738-12.537-.2-23.614 2.533-33.079 8.15-5.24-1.772-13.65-4.27-23.362-5.864-22.842-3.75-41.252-.828-54.718 8.685C6.622 25.672-.937 45.684.461 73.634c.444 8.874 5.408 35.874 13.224 61.48 4.492 14.718 9.282 26.94 14.237 36.33 7.027 13.315 14.546 21.156 22.987 23.972 4.731 1.576 13.327 2.68 22.368-4.85 1.146 1.388 2.675 2.767 4.704 4.048 2.577 1.625 5.728 2.953 8.875 3.74 11.341 2.835 21.964 2.126 31.027-1.848.056 1.612.099 3.152.135 4.482.06 2.157.12 4.272.199 6.25.537 13.374 1.447 23.773 4.143 31.049.148.4.347 1.01.557 1.657 1.345 4.118 3.594 11.012 9.316 16.411 5.925 5.593 13.092 7.308 19.656 7.308 3.292 0 6.433-.432 9.188-1.022 9.82-2.105 20.973-5.311 29.041-16.799 7.628-10.86 11.336-27.217 12.007-52.99.087-.729.167-1.425.244-2.088l.16-1.362 1.797.158.463.031c10.002.456 22.232-1.665 29.743-5.154 5.935-2.754 24.954-12.795 20.476-26.351" fill="#336791"/>
+ <path d="M237.906 160.722c-29.74 6.135-31.785-3.934-31.785-3.934 31.4-46.593 44.527-105.736 33.2-120.211-30.904-39.485-84.399-20.811-85.292-20.327l-.287.052c-5.876-1.22-12.451-1.946-19.842-2.067-13.456-.22-23.664 3.528-31.41 9.402 0 0-95.43-39.314-90.991 49.444.944 18.882 27.064 142.873 58.218 105.422 11.387-13.695 22.39-25.274 22.39-25.274 5.464 3.63 12.006 5.482 18.864 4.817l.533-.452c-.166 1.7-.09 3.363.213 5.332-8.026 8.967-5.667 10.541-21.711 13.844-16.235 3.346-6.698 9.302-.471 10.86 7.549 1.887 25.013 4.561 36.813-11.958l-.47 1.885c3.144 2.519 5.352 16.383 4.982 28.952-.37 12.568-.617 21.197 1.86 27.937 2.479 6.74 4.948 21.905 26.04 17.386 17.623-3.777 26.756-13.564 28.027-29.89.901-11.606 2.942-9.89 3.07-20.267l1.637-4.912c1.887-15.733.3-20.809 11.157-18.448l2.64.232c7.99.363 18.45-1.286 24.589-4.139 13.218-6.134 21.058-16.377 8.024-13.686h.002" fill="#FFF"/>
+ <path d="M108.076 81.525c-2.68-.373-5.107-.028-6.335.902-.69.523-.904 1.129-.962 1.546-.154 1.105.62 2.327 1.096 2.957 1.346 1.784 3.312 3.01 5.258 3.28.282.04.563.058.842.058 3.245 0 6.196-2.527 6.456-4.392.325-2.336-3.066-3.893-6.355-4.351M196.86 81.599c-.256-1.831-3.514-2.353-6.606-1.923-3.088.43-6.082 1.824-5.832 3.659.2 1.427 2.777 3.863 5.827 3.863.258 0 .518-.017.78-.054 2.036-.282 3.53-1.575 4.24-2.32 1.08-1.136 1.706-2.402 1.591-3.225" fill="#336791"/>
+ <path d="M247.802 160.025c-1.134-3.429-4.784-4.532-10.848-3.28-18.005 3.716-24.453 1.142-26.57-.417 13.995-21.32 25.508-47.092 31.719-71.137 2.942-11.39 4.567-21.968 4.7-30.59.147-9.463-1.465-16.417-4.789-20.665-13.402-17.125-33.072-26.311-56.882-26.563-16.369-.184-30.199 4.005-32.88 5.183-5.646-1.404-11.801-2.266-18.502-2.376-12.288-.199-22.91 2.743-31.704 8.74-3.82-1.422-13.692-4.811-25.765-6.756-20.872-3.36-37.458-.814-49.294 7.571-14.123 10.006-20.643 27.892-19.38 53.16.425 8.501 5.269 34.653 12.913 59.698 10.062 32.964 21 51.625 32.508 55.464 1.347.449 2.9.763 4.613.763 4.198 0 9.345-1.892 14.7-8.33a529.832 529.832 0 0 1 20.261-22.926c4.524 2.428 9.494 3.784 14.577 3.92.01.133.023.266.035.398a117.66 117.66 0 0 0-2.57 3.175c-3.522 4.471-4.255 5.402-15.592 7.736-3.225.666-11.79 2.431-11.916 8.435-.136 6.56 10.125 9.315 11.294 9.607 4.074 1.02 7.999 1.523 11.742 1.523 9.103 0 17.114-2.992 23.516-8.781-.197 23.386.778 46.43 3.586 53.451 2.3 5.748 7.918 19.795 25.664 19.795 2.123 0 4.441-.197 6.959-.592 17.856-2.805 25.723-12.098 27.064-31.952.807-11.934 2.17-10.333 3.235-20.761l.068-.593a.266.266 0 0 1 .068-.088l.627-5.458c1.455-11.273 1.068-15.16 9.333-14.03l2.222.197c7.137.457 15.92-.805 21.39-3.296 13.59-6.189 20.084-15.006 17.55-22.68" fill="#FFF"/>
+ <path d="M99.14 72.896c-2.668-.378-5.097-.028-6.326.903-.69.523-.904 1.128-.963 1.546-.153 1.105.62 2.326 1.097 2.956 1.345 1.784 3.31 3.01 5.257 3.28a8.59 8.59 0 0 0 .84.059c3.245 0 6.196-2.527 6.457-4.392.325-2.336-3.066-3.893-6.354-4.352m-28.082 2.76c.326 2.339 3.066 3.894 6.356 4.353 2.67.378 5.097.029 6.325-.903.691-.523.906-1.128.964-1.546.152-1.104-.622-2.326-1.097-2.956-1.345-1.784-3.312-3.01-5.256-3.28a8.582 8.582 0 0 0-.842-.058c-3.245 0-6.196 2.527-6.456 4.392M110.04 152.68c-6.43 7.282-12.66 9.383-15.918 8.29-3.993-1.34-8.682-7.31-13.628-17.376-4.996-10.168-9.452-22.85-12.552-35.715-6.314-26.17-9.24-50.027-9.47-53.609-.55-8.594.756-15.639 3.886-20.946 5.58-9.462 16.257-14.156 31.74-13.946 10.458.142 20.455 2.165 24.896 3.435-6.453 5.298-10.358 12.276-11.78 20.994-.884 5.42-.752 11.09.39 16.85.026.153 2.563 14.66 12.18 25.343a7.997 7.997 0 0 1 1.858 3.848c.26 1.56.043 3.28-.704 4.893a8.037 8.037 0 0 1-2.112 2.76 11.158 11.158 0 0 0-3.324 5.063c-.573 1.86-.58 3.757-.024 5.648 1.548 5.26 5.732 10.46 9.116 13.946 1.692 1.742 3.42 3.54 5.45 4.966 1.44 1.013 3.168 1.89 4.955 2.407-.587.695-1.183 1.396-1.79 2.108-2.074 2.434-4.09 4.678-6.003 6.675-7.146 7.457-11.155 11.635-17.166 20.37M172.178 60.116c-.263-4.315-1.983-8.152-5.227-11.603-1.405-1.495-3.187-2.79-5.39-3.845-2.083-.996-4.502-1.79-7.197-2.36-2.252-.476-4.667-.778-7.157-.924.112-.312.23-.62.34-.937 1.217-3.425 3.128-8.803 2.45-15.165-.8-7.512-5.096-13.423-12.778-17.583-3.654-1.978-7.65-3.224-11.693-3.667-4.095-.45-8.17-.239-11.96.603-1.32.293-2.6.64-3.793 1.027 8.168-4.776 18.155-6.973 29.394-6.789 14.659.24 26.75 5.13 36.01 14.546 6.13 6.233 9.367 13.3 9.621 21.002.25 7.57-3.375 14.798-6.755 20.159-.757 1.2-1.54 2.374-2.354 3.534-.213-1.044-.562-1.99-1.042-2.83-.622-1.09-1.454-2.034-2.478-2.156m-29.29 128.142c-.443 12.556-.618 21.172 1.856 27.918 1.474 4.022 3.422 10.033 8.638 14.123 4.77 3.742 10.553 4.569 16.197 4.341a98.59 98.59 0 0 0 2.944-.136c16.12-1.153 22.568-8.952 24.253-26.278.94-9.655 2.659-10.618 3.61-19.556l.662-5.767c1.193-9.27 1.401-11.704 5.63-15.014 3.038-2.38 5.804-2.86 10.276-2.076l2.197.193c4.85.31 10.662.33 15.425-1.122-1.758.57-3.556 1.18-5.285 1.85-5.28 2.043-15.32 8.028-13.333 15.97.53 2.12 1.73 3.842 3.464 5.009 2.665 1.795 6.275 2.446 9.87 2.446 2.246 0 4.487-.219 6.515-.6 1.556-.292 3.223-.702 4.78-1.224a29.45 29.45 0 0 1-4.004 1.824c-5.987 2.271-14.255 3.308-20.632 2.587-3.88-.439-7.276-2.202-8.94-4.639l.035.04c-3.305-4.839-1.987-13.027-1.38-17.17l.05-.317c.01-.063.023-.136.04-.213l.685-5.57c1.498-11.559 1.23-15.648 9.737-14.264l2.207.193c6.992.452 15.548-.786 20.816-3.191 8.28-3.78 17.078-11.08 17.078-17.942 0-3.5-2.104-5.13-4.94-5.13-4.638 0-11.83 3.56-16.83 5.843-4.708 2.152-10.38 3.092-16.28 2.71a76.86 76.86 0 0 1-4.23-.378c-10.416-1.09-23.22-4.473-33.792-13.048-5.56-4.506-10.085-9.376-13.625-14.609.035.06.076.114.11.174.632 1.08 1.49 2.022 2.522 2.14.906.106 1.828-.303 2.652-.78-.596 3.227-.498 6.564.254 9.81.03.13.066.26.096.39 2.106 9.14 8.293 16.402 15.596 20.38 2.094 1.14 4.315 2.02 6.575 2.674 2.326.675 4.7 1.087 7.04 1.283.14.013.274.019.414.029.26.019.522.028.784.047 1.087.074 2.167.118 3.237.125 3.27.02 6.476-.255 9.495-.836 1.635-.316 3.225-.725 4.773-1.211 2.82.236 5.727.105 8.608-.384a48.43 48.43 0 0 0 5.95-1.345c-.218.26-.433.522-.658.773-5.416 6.033-12.85 9.63-19.778 9.573l-.036-.002c-.99-.007-1.952-.076-2.878-.193-.01-.002-.02-.002-.029-.002l-.006.008a11.65 11.65 0 0 1-2.21-.463c-1.704-.495-3.32-1.272-4.79-2.282-2.05-1.413-3.814-3.285-5.483-5.037-3.34-3.441-7.46-8.58-9.018-13.876a11.673 11.673 0 0 1-.05-6.38c.463-1.767 1.352-3.404 2.696-4.884a10.82 10.82 0 0 0 2.89-5.323c.355-1.894.18-3.865-.457-5.883-.88-2.781-2.529-5.26-4.384-7.38a37.55 37.55 0 0 1-2.8-3.424c-6.69-9.015-8.57-19.792-8.91-23.405l-.003-.008c-.003-.013-.003-.022-.003-.026-1.146-5.714-1.235-11.184-.357-16.552 1.384-8.484 5.323-15.195 12.088-20.035 5.81-4.156 12.78-6.293 20.07-6.293.376 0 .756.005 1.135.014l.29.007a86.96 86.96 0 0 1 7.137.712c2.826.418 5.454 1.023 7.738 1.713 2.315.7 4.398 1.533 6.089 2.341 2.177 1.04 3.936 2.33 5.354 3.835 2.88 3.063 4.478 6.584 4.712 10.423.25 4.096-.96 8.437-2.165 12.39l-.116.382-.007.03c-.178.585-.362 1.175-.556 1.78-1.58 4.921-3.46 9.884-5.533 14.89a285.994 285.994 0 0 1-4.01 9.088c-1.407 3.06-2.91 6.155-4.476 9.248-1.635 3.226-3.347 6.468-5.092 9.676-3.04 5.593-6.276 11.26-9.552 16.66-3.281 5.407-6.628 10.585-9.881 15.414a272.27 272.27 0 0 1-5.012 7.114c-1.46 2.003-2.924 3.998-4.383 5.987l-.44.6a.57.57 0 0 0-.029.041.588.588 0 0 0-.01.025l-4.16 5.674c-4.685 6.387-9.496 12.778-14.297 19.125l-.04.053c-.51.678-1.023 1.343-1.532 2.018-10.02 13.283-15.18 22.093-15.56 42.22M85.963 95.78c-.316 2.268 3.073 4.512 6.37 4.97 2.653.37 5.18.04 6.481-.945.704-.534.91-1.13.966-1.566.155-1.106-.63-2.478-1.106-3.125-1.38-1.87-3.522-3.16-5.46-3.43a7.67 7.67 0 0 0-.91-.063c-3.147 0-5.974 1.971-6.341 4.16" fill="#336791"/>
+ </svg>
+ }
+ iconType="duotone"
+ >
+ </Card>
+</CardGroup>
+
### VectorDBs
<CardGroup cols={2}>
<Card
diff --git a/docs/latest/sdk/integrations/psycopg.mdx b/docs/latest/sdk/integrations/psycopg.mdx
new file mode 100644
index 00000000..6f7231e6
--- /dev/null
+++ b/docs/latest/sdk/integrations/psycopg.mdx
@@ -0,0 +1,117 @@
+---
+title: 'Monitor PostgreSQL (psycopg3) using OpenTelemetry'
+sidebarTitle: 'PostgreSQL (psycopg3)'
+---
+
+import IntegrationMethods from '/snippets/integration-methods.mdx';
+
+OpenLIT uses OpenTelemetry Auto-Instrumentation to help you monitor applications using PostgreSQL with the psycopg3 driver. This includes tracking query performance, transaction operations, connection pool metrics, and more.
+
+Auto-instrumentation means you don't have to set up monitoring manually for different databases or query types. By simply adding OpenLIT in your application, all the necessary monitoring configurations are automatically set up.
+
+The integration is compatible with
+- psycopg `>= 3.0.0`
+- psycopg_pool (optional, for connection pool monitoring)
+
+## Supported Operations
+
+| Operation | Description |
+|-----------|-------------|
+| `execute` | Single query execution |
+| `executemany` | Batch query execution |
+| `copy` | COPY operations for bulk data transfer |
+| `callproc` | Stored procedure calls |
+| `commit` | Transaction commits |
+| `rollback` | Transaction rollbacks |
+
+## PostgreSQL-Specific Features
+
+OpenLIT automatically detects and enriches traces with PostgreSQL-specific features:
+
+- **pgvector Support**: Detects vector similarity operators (`<=>`, `<->`, `<#>`) and records the similarity metric (cosine, L2, inner product)
+- **Full-Text Search**: Detects `tsvector`, `tsquery`, `websearch_to_tsquery`, and `ts_rank` operations
+
+## Get started
+
+<Steps>
+ <Step title="Install OpenLIT">
+ Open your command line or terminal and run:
+ ```shell
+ pip install openlit
+ ```
+ </Step>
+ <IntegrationMethods />
+</Steps>
+
+## Advanced Configuration
+
+### Database-Specific Options
+
+OpenLIT provides additional configuration options for database instrumentation:
+
+| Parameter | Environment Variable | Description | Default |
+|-----------|---------------------|-------------|---------|
+| `capture_parameters` | `OPENLIT_CAPTURE_PARAMETERS` | Capture query parameters in spans | `False` |
+| `enable_sqlcommenter` | `OPENLIT_ENABLE_SQLCOMMENTER` | Inject trace context as SQL comments | `False` |
+
+### capture_parameters
+
+When enabled, query parameters are recorded in span attributes for debugging purposes.
+
+```python
+import openlit
+
+openlit.init(capture_parameters=True)
+```
+
+<Warning>
+**Security Risk**: Enabling `capture_parameters` may expose sensitive data like passwords, tokens, or PII in your traces. Only enable in development environments or when you're certain parameters don't contain sensitive information.
+</Warning>
+
+### enable_sqlcommenter (SQLCommenter)
+
+When enabled, OpenLIT injects OpenTelemetry trace context into SQL queries as comments. This enables correlation between application traces and database logs.
+
+```python
+import openlit
+
+openlit.init(enable_sqlcommenter=True)
+```
+
+**Example query transformation:**
+
+```sql
+-- Original query
+SELECT * FROM users WHERE id = $1;
+
+-- With SQLCommenter enabled
+SELECT * FROM users WHERE id = $1 /*traceparent='00-abc123def456-789xyz-01',application='my_app'*/;
+```
+
+**Benefits:**
+- Correlate slow queries in `pg_stat_statements` with application traces
+- Link `EXPLAIN ANALYZE` output to specific requests
+- Debug performance issues across application and database layers
+
+---
+
+<CardGroup cols={3}>
+ <Card title="Quickstart: Database Observability" href="/latest/sdk/quickstart-vectordb-observability" icon='bolt'>
+ Production-ready database monitoring setup in 2 simple steps
+ </Card>
+ <Card title="Configuration" href="/latest/sdk/configuration" icon='bolt'>
+ Configure the OpenLIT SDK according to your requirements.
+ </Card>
+ <Card title="Destinations" href="/latest/sdk/destinations/overview" icon='link'>
+ Send telemetry to Datadog, Grafana, New Relic, and other observability stacks
+ </Card>
+</CardGroup>
+<Card
+ title="Running in Kubernetes? Try the OpenLIT Operator"
+ icon={<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
+ <title>Kubernetes</title>
+ <path fill="#FFA500" d="M10.204 14.35l.007.01-.999 2.413a5.171 5.171 0 0 1-2.075-2.597l2.578-.437.004.005a.44.44 0 0 1 .484.606zm-.833-2.129a.44.44 0 0 0 .173-.756l.002-.011L7.585 9.7a5.143 5.143 0 0 0-.73 3.255l2.514-.725.002-.009zm1.145-1.98a.44.44 0 0 0 .699-.337l.01-.005.15-2.62a5.144 5.144 0 0 0-3.01 1.442l2.147 1.523.004-.002zm.76 2.75l.723.349.722-.347.18-.78-.5-.623h-.804l-.5.623.179.779zm1.5-3.095a.44.44 0 0 0 .7.336l.008.003 2.134-1.513a5.188 5.188 0 0 0-2.992-1.442l.148 2.615.002.001zm10.876 5.97l-5.773 7.181a1.6 1.6 0 0 1-1.248.594l-9.261.003a1.6 1.6 0 0 1-1.247-.596l-5.776-7.18a1.583 1.583 0 0 1-.307-1.34L2.1 5.573c.108-.47.425-.864.863-1.073L11.305.513a1.606 1.606 0 0 1 1.385 0l8.345 3.985c.438.209.755.604.863 1.073l2.062 8.955c.108.47-.005.963-.308 1.34zm-3.289-2.057c-.042-.01-.103-.026-.145-.034-.174-.033-.315-.025-.479-.038-.35-.037-.638-.067-.895-.148-.105-.04-.18-.165-.216-.216l-.201-.059a6.45 6.45 0 0 0-.105-2.332 6.465 6.465 0 0 0-.936-2.163c.052-.047.15-.133.177-.159.008-.09.001-.183.094-.282.197-.185.444-.338.743-.522.142-.084.273-.137.415-.242.032-.024.076-.062.11-.089.24-.191.295-.52.123-.736-.172-.216-.506-.236-.745-.045-.034.027-.08.062-.111.088-.134.116-.217.23-.33.35-.246.25-.45.458-.673.609-.097.056-.239.037-.303.033l-.19.135a6.545 6.545 0 0 0-4.146-2.003l-.012-.223c-.065-.062-.143-.115-.163-.25-.022-.268.015-.557.057-.905.023-.163.061-.298.068-.475.001-.04-.001-.099-.001-.142 0-.306-.224-.555-.5-.555-.275 0-.499.249-.499.555l.001.014c0 .041-.002.092 0 .128.006.177.044.312.067.475.042.348.078.637.056.906a.545.545 0 0 1-.162.258l-.012.211a6.424 6.424 0 0 0-4.166 2.003 8.373 8.373 0 0 1-.18-.128c-.09.012-.18.04-.297-.029-.223-.15-.427-.358-.673-.608-.113-.12-.195-.234-.329-.349-.03-.026-.077-.062-.111-.088a.594.594 0 0 0-.348-.132.481.481 0 0 0-.398.176c-.172.216-.117.546.123.737l.007.005.104.083c.142.105.272.159.414.242.299.185.546.338.743.522.076.082.09.226.1.288l.16.143a6.462 6.462 0 0 0-1.02 4.506l-.208.06c-.055.072-.133.184-.215.217-.257.081-.546.11-.895.147-.164.014-.305.006-.48.039-.037.007-.09.02-.133.03l-.004.002-.007.002c-.295.071-.484.342-.423.608.061.267.349.429.645.365l.007-.001.01-.003.129-.029c.17-.046.294-.113.448-.172.33-.118.604-.217.87-.256.112-.009.23.069.288.101l.217-.037a6.5 6.5 0 0 0 2.88 3.596l-.09.218c.033.084.069.199.044.282-.097.252-.263.517-.452.813-.091.136-.185.242-.268.399-.02.037-.045.095-.064.134-.128.275-.034.591.213.71.248.12.556-.007.69-.282v-.002c.02-.039.046-.09.062-.127.07-.162.094-.301.144-.458.132-.332.205-.68.387-.897.05-.06.13-.082.215-.105l.113-.205a6.453 6.453 0 0 0 4.609.012l.106.192c.086.028.18.042.256.155.136.232.229.507.342.84.05.156.074.295.145.457.016.037.043.09.062.129.133.276.442.402.69.282.247-.118.341-.435.213-.71-.02-.039-.045-.096-.065-.134-.083-.156-.177-.261-.268-.398-.19-.296-.346-.541-.443-.793-.04-.13.007-.21.038-.294-.018-.022-.059-.144-.083-.202a6.499 6.499 0 0 0 2.88-3.622c.064.01.176.03.213.038.075-.05.144-.114.28-.104.266.039.54.138.87.256.154.06.277.128.448.173.036.01.088.019.13.028l.009.003.007.001c.297.064.584-.098.645-.365.06-.266-.128-.537-.423-.608zM16.4 9.701l-1.95 1.746v.005a.44.44 0 0 0 .173.757l.003.01 2.526.728a5.199 5.199 0 0 0-.108-1.674A5.208 5.208 0 0 0 16.4 9.7zm-4.013 5.325a.437.437 0 0 0-.404-.232.44.44 0 0 0-.372.233h-.002l-1.268 2.292a5.164 5.164 0 0 0 3.326.003l-1.27-2.296h-.01zm1.888-1.293a.44.44 0 0 0-.27.036.44.44 0 0 0-.214.572l-.003.004 1.01 2.438a5.15 5.15 0 0 0 2.081-2.615l-2.6-.44-.004.005z"/></svg>}
+ href="/latest/operator/overview"
+ >
+ Automatically inject instrumentation into existing workloads without modifying pod specs, container images, or application code.
+ </Card>
diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml
index 519d7e8c..46d50239 100644
--- a/sdk/python/pyproject.toml
+++ b/sdk/python/pyproject.toml
@@ -1,6 +1,6 @@
[tool.poetry]
name = "openlit"
-version = "1.36.6"
+version = "1.36.7"
description = "OpenTelemetry-native Auto instrumentation library for monitoring LLM Applications and GPUs, facilitating the integration of observability into your GenAI-driven projects"
authors = ["OpenLIT"]
license = "Apache-2.0"
diff --git a/sdk/python/src/openlit/__init__.py b/sdk/python/src/openlit/__init__.py
index cba910fd..6b814aac 100644
--- a/sdk/python/src/openlit/__init__.py
+++ b/sdk/python/src/openlit/__init__.py
@@ -79,6 +79,9 @@ class OpenlitConfig:
cls.capture_message_content = True
cls.disable_metrics = False
cls.detailed_tracing = True
+ # Database instrumentation options
+ cls.capture_parameters = False
+ cls.enable_sqlcommenter = False
@classmethod
def update_config(
@@ -95,6 +98,8 @@ class OpenlitConfig:
disable_metrics,
pricing_json,
detailed_tracing,
+ capture_parameters=False,
+ enable_sqlcommenter=False,
):
"""
Updates the configuration based on provided parameters.
@@ -113,6 +118,8 @@ class OpenlitConfig:
disable_metrics (bool): Flag to disable metrics.
pricing_json(str): path or url to the pricing json file
detailed_tracing (bool): Flag to enable detailed component-level tracing.
+ capture_parameters (bool): Capture database query parameters (security risk).
+ enable_sqlcommenter (bool): Inject trace context as SQL comments.
"""
cls.environment = environment
cls.application_name = application_name
@@ -126,6 +133,8 @@ class OpenlitConfig:
cls.capture_message_content = capture_message_content
cls.disable_metrics = disable_metrics
cls.detailed_tracing = detailed_tracing
+ cls.capture_parameters = capture_parameters
+ cls.enable_sqlcommenter = enable_sqlcommenter
def module_exists(module_name):
@@ -188,6 +197,8 @@ def instrument_if_available(
metrics_dict=config.metrics_dict,
disable_metrics=config.disable_metrics,
detailed_tracing=config.detailed_tracing,
+ capture_parameters=config.capture_parameters,
+ enable_sqlcommenter=config.enable_sqlcommenter,
)
else:
logger.info(
@@ -216,6 +227,8 @@ def init(
collect_gpu_stats=False,
detailed_tracing=True,
collect_system_metrics=False,
+ capture_parameters=False,
+ enable_sqlcommenter=False,
):
"""
Initializes the openLIT configuration and setups tracing.
@@ -291,6 +304,10 @@ def init(
detailed_tracing = env_config["detailed_tracing"]
if collect_system_metrics is False and "collect_system_metrics" in env_config:
collect_system_metrics = env_config["collect_system_metrics"]
+ if capture_parameters is False and "capture_parameters" in env_config:
+ capture_parameters = env_config["capture_parameters"]
+ if enable_sqlcommenter is False and "enable_sqlcommenter" in env_config:
+ enable_sqlcommenter = env_config["enable_sqlcommenter"]
except ImportError:
# Fallback if config module is not available - continue without env var support
@@ -373,6 +390,8 @@ def init(
disable_metrics,
pricing_json,
detailed_tracing,
+ capture_parameters,
+ enable_sqlcommenter,
)
# Create instrumentor instances dynamically
diff --git a/sdk/python/src/openlit/_instrumentors.py b/sdk/python/src/openlit/_instrumentors.py
index 78eb366f..7998612a 100644
--- a/sdk/python/src/openlit/_instrumentors.py
+++ b/sdk/python/src/openlit/_instrumentors.py
@@ -54,6 +54,9 @@ MODULE_NAME_MAP = {
"sarvam": "sarvamai",
"browser-use": "browser_use",
"mcp": "mcp",
+ # Database instrumentations
+ "psycopg": "psycopg",
+ "psycopg-pool": "psycopg_pool",
# Official OpenTelemetry HTTP Framework instrumentations
"asgi": "asgiref",
"django": "django",
@@ -121,6 +124,9 @@ INSTRUMENTOR_MAP = {
"sarvam": "openlit.instrumentation.sarvam.SarvamInstrumentor",
"browser-use": "openlit.instrumentation.browser_use.BrowserUseInstrumentor",
"mcp": "openlit.instrumentation.mcp.MCPInstrumentor",
+ # Database instrumentations
+ "psycopg": "openlit.instrumentation.psycopg.PsycopgInstrumentor",
+ "psycopg-pool": "openlit.instrumentation.psycopg.PsycopgInstrumentor",
# Official OpenTelemetry HTTP Framework instrumentations
"asgi": "opentelemetry.instrumentation.asgi.AsgiInstrumentor",
"django": "opentelemetry.instrumentation.django.DjangoInstrumentor",
diff --git a/sdk/python/src/openlit/cli/bootstrap/sitecustomize.py b/sdk/python/src/openlit/cli/bootstrap/sitecustomize.py
index bf09d03b..69004fac 100644
--- a/sdk/python/src/openlit/cli/bootstrap/sitecustomize.py
+++ b/sdk/python/src/openlit/cli/bootstrap/sitecustomize.py
@@ -38,6 +38,8 @@ except ImportError:
"OPENLIT_COLLECT_GPU_STATS": "collect_gpu_stats",
"OPENLIT_DETAILED_TRACING": "detailed_tracing",
"OPENLIT_PRICING_JSON": "pricing_json",
+ "OPENLIT_CAPTURE_PARAMETERS": "capture_parameters",
+ "OPENLIT_ENABLE_SQLCOMMENTER": "enable_sqlcommenter",
}
for env_var, param_name in env_mappings.items():
@@ -49,6 +51,8 @@ except ImportError:
"OPENLIT_DISABLE_METRICS",
"OPENLIT_COLLECT_GPU_STATS",
"OPENLIT_DETAILED_TRACING",
+ "OPENLIT_CAPTURE_PARAMETERS",
+ "OPENLIT_ENABLE_SQLCOMMENTER",
]:
config[param_name] = env_value.lower() in ("true", "1", "yes")
# Handle CSV values
diff --git a/sdk/python/src/openlit/cli/config.py b/sdk/python/src/openlit/cli/config.py
index 42fb1998..bb3e796d 100644
--- a/sdk/python/src/openlit/cli/config.py
+++ b/sdk/python/src/openlit/cli/config.py
@@ -98,6 +98,18 @@ PARAMETER_CONFIG = {
"cli_help": "Enable comprehensive system metrics (CPU, memory, disk, network, GPU if detected)",
"cli_type": bool,
},
+ "capture_parameters": {
+ "default": False,
+ "env_var": "OPENLIT_CAPTURE_PARAMETERS",
+ "cli_help": "Capture database query parameters in spans (security risk - may expose sensitive data)",
+ "cli_type": bool,
+ },
+ "enable_sqlcommenter": {
+ "default": False,
+ "env_var": "OPENLIT_ENABLE_SQLCOMMENTER",
+ "cli_help": "Inject OpenTelemetry trace context as SQL comments for database log correlation",
+ "cli_type": bool,
+ },
# Parameters that are not exposed via CLI (internal use only)
"tracer": {
"default": None,
diff --git a/sdk/python/src/openlit/instrumentation/psycopg/__init__.py b/sdk/python/src/openlit/instrumentation/psycopg/__init__.py
new file mode 100644
index 00000000..80ed3886
--- /dev/null
+++ b/sdk/python/src/openlit/instrumentation/psycopg/__init__.py
@@ -0,0 +1,538 @@
+"""
+OpenLIT Psycopg (PostgreSQL) Instrumentation
+"""
+
+from typing import Collection, Any, Optional
+import importlib.metadata
+import functools
+from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
+from wrapt import wrap_function_wrapper
+
+from openlit.instrumentation.psycopg.psycopg import (
+ execute_wrap,
+ executemany_wrap,
+ copy_wrap,
+ commit_wrap,
+ rollback_wrap,
+ callproc_wrap,
+ pool_getconn_wrap,
+)
+from openlit.instrumentation.psycopg.async_psycopg import (
+ async_execute_wrap,
+ async_executemany_wrap,
+ async_copy_wrap,
+ async_commit_wrap,
+ async_rollback_wrap,
+ async_callproc_wrap,
+ async_pool_getconn_wrap,
+)
+
+_instruments = ("psycopg >= 3.0.0",)
+
+# Cursor operations to wrap (method_name, endpoint_name)
+CURSOR_OPERATIONS = [
+ ("execute", "psycopg.cursor.execute"),
+ ("executemany", "psycopg.cursor.executemany"),
+ ("copy", "psycopg.cursor.copy"),
+ ("callproc", "psycopg.cursor.callproc"),
+]
+
+# Connection operations to wrap
+CONNECTION_OPERATIONS = [
+ ("commit", "psycopg.connection.commit"),
+ ("rollback", "psycopg.connection.rollback"),
+]
+
+# Cursor class mappings
+SYNC_CURSOR_CLASSES = [
+ "Cursor",
+ "ClientCursor",
+ "ServerCursor",
+ "RawCursor",
+]
+
+ASYNC_CURSOR_CLASSES = [
+ "AsyncCursor",
+ "AsyncClientCursor",
+ "AsyncServerCursor",
+ "AsyncRawCursor",
+]
+
+# Wrapper function mappings for cursor operations
+SYNC_CURSOR_WRAPPERS = {
+ "execute": execute_wrap,
+ "executemany": executemany_wrap,
+ "copy": copy_wrap,
+ "callproc": callproc_wrap,
+}
+
+ASYNC_CURSOR_WRAPPERS = {
+ "execute": async_execute_wrap,
+ "executemany": async_executemany_wrap,
+ "copy": async_copy_wrap,
+ "callproc": async_callproc_wrap,
+}
+
+# Wrapper function mappings for connection operations
+SYNC_CONNECTION_WRAPPERS = {
+ "commit": commit_wrap,
+ "rollback": rollback_wrap,
+}
+
+ASYNC_CONNECTION_WRAPPERS = {
+ "commit": async_commit_wrap,
+ "rollback": async_rollback_wrap,
+}
+
+
+class PsycopgInstrumentor(BaseInstrumentor):
+ """
+ An instrumentor for Psycopg (PostgreSQL) library.
+
+ This instrumentor wraps:
+ - Cursor.execute, executemany, copy, callproc (sync and async)
+ - Connection.commit, rollback (sync and async)
+ - ConnectionPool operations (optional, from psycopg_pool)
+
+ Configuration Options:
+ - capture_parameters: If True, captures query parameters in spans.
+ WARNING: This may expose sensitive data like passwords, PII, tokens.
+ Only enable in development or when you're certain parameters are safe.
+ Default: False
+
+ - enable_sqlcommenter: If True, injects OpenTelemetry trace context as SQL
+ comments (SQLCommenter format). This enables correlation between
+ application traces and database logs (pg_stat_statements, auto_explain).
+ Default: False
+ """
+
+ def instrumentation_dependencies(self) -> Collection[str]:
+ return _instruments
+
+ def _instrument(self, **kwargs):
+ # Get psycopg version
+ try:
+ version = importlib.metadata.version("psycopg")
+ except importlib.metadata.PackageNotFoundError:
+ version = "unknown"
+
+ environment = kwargs.get("environment", "default")
+ application_name = kwargs.get("application_name", "default")
+ tracer = kwargs.get("tracer")
+ pricing_info = kwargs.get("pricing_info", {})
+ capture_message_content = kwargs.get("capture_message_content", False)
+ metrics = kwargs.get("metrics_dict")
+ disable_metrics = kwargs.get("disable_metrics")
+
+ # New configuration options
+ capture_parameters = kwargs.get("capture_parameters", False)
+ enable_sqlcommenter = kwargs.get("enable_sqlcommenter", False)
+
+ # Wrap sync cursor operations
+ for cursor_class in SYNC_CURSOR_CLASSES:
+ for method_name, endpoint in CURSOR_OPERATIONS:
+ wrapper_func = SYNC_CURSOR_WRAPPERS.get(method_name)
+ if wrapper_func:
+ try:
+ wrap_function_wrapper(
+ "psycopg",
+ f"{cursor_class}.{method_name}",
+ wrapper_func(
+ endpoint,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters,
+ enable_sqlcommenter,
+ ),
+ )
+ except Exception:
+ # Class might not exist in all psycopg versions
+ pass
+
+ # Wrap async cursor operations
+ for cursor_class in ASYNC_CURSOR_CLASSES:
+ for method_name, endpoint in CURSOR_OPERATIONS:
+ wrapper_func = ASYNC_CURSOR_WRAPPERS.get(method_name)
+ if wrapper_func:
+ try:
+ wrap_function_wrapper(
+ "psycopg",
+ f"{cursor_class}.{method_name}",
+ wrapper_func(
+ endpoint,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters,
+ enable_sqlcommenter,
+ ),
+ )
+ except Exception:
+ # Class might not exist in all psycopg versions
+ pass
+
+ # Wrap sync connection operations
+ for method_name, endpoint in CONNECTION_OPERATIONS:
+ wrapper_func = SYNC_CONNECTION_WRAPPERS.get(method_name)
+ if wrapper_func:
+ try:
+ wrap_function_wrapper(
+ "psycopg",
+ f"Connection.{method_name}",
+ wrapper_func(
+ endpoint,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters,
+ enable_sqlcommenter,
+ ),
+ )
+ except Exception:
+ pass
+
+ # Wrap async connection operations
+ for method_name, endpoint in CONNECTION_OPERATIONS:
+ wrapper_func = ASYNC_CONNECTION_WRAPPERS.get(method_name)
+ if wrapper_func:
+ try:
+ wrap_function_wrapper(
+ "psycopg",
+ f"AsyncConnection.{method_name}",
+ wrapper_func(
+ endpoint,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters,
+ enable_sqlcommenter,
+ ),
+ )
+ except Exception:
+ pass
+
+ # Try to instrument psycopg_pool if available
+ self._instrument_pool(
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters,
+ enable_sqlcommenter,
+ )
+
+ def _instrument_pool(
+ self,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters=False,
+ enable_sqlcommenter=False,
+ ):
+ """
+ Instrument psycopg_pool connection pool operations.
+ """
+ try:
+ # Try to get psycopg_pool version
+ pool_version = importlib.metadata.version("psycopg-pool")
+ except importlib.metadata.PackageNotFoundError:
+ # psycopg_pool not installed, skip pool instrumentation
+ return
+
+ # Wrap sync ConnectionPool.getconn
+ try:
+ wrap_function_wrapper(
+ "psycopg_pool",
+ "ConnectionPool.getconn",
+ pool_getconn_wrap(
+ "psycopg.pool.getconn",
+ pool_version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters,
+ enable_sqlcommenter,
+ ),
+ )
+ except Exception:
+ pass
+
+ # Wrap async AsyncConnectionPool.getconn
+ try:
+ wrap_function_wrapper(
+ "psycopg_pool",
+ "AsyncConnectionPool.getconn",
+ async_pool_getconn_wrap(
+ "psycopg.pool.async_getconn",
+ pool_version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters,
+ enable_sqlcommenter,
+ ),
+ )
+ except Exception:
+ pass
+
+ @classmethod
+ def instrument_connection(
+ cls,
+ connection: Any,
+ tracer: Optional[Any] = None,
+ environment: str = "default",
+ application_name: str = "default",
+ capture_parameters: bool = False,
+ enable_sqlcommenter: bool = False,
+ capture_message_content: bool = True,
+ **kwargs,
+ ) -> Any:
+ """
+ Instrument a single psycopg Connection or AsyncConnection instance.
+
+ This method allows granular control over which connections are instrumented
+ and with what settings. Useful for:
+ - Multi-tenant apps with selective tracing
+ - Testing scenarios
+ - Connections with different security requirements
+ - Instrumenting connections from external pools
+
+ Args:
+ connection: A psycopg Connection or AsyncConnection instance
+ tracer: Optional OpenTelemetry tracer instance
+ environment: Deployment environment name
+ application_name: Application name for tracing
+ capture_parameters: Capture query parameters in spans (security risk!)
+ enable_sqlcommenter: Inject trace context as SQL comments
+ capture_message_content: Capture SQL query text
+
+ Returns:
+ The instrumented connection (same instance, modified in place)
+
+ Example:
+ ```python
+ import psycopg
+ from openlit.instrumentation.psycopg import PsycopgInstrumentor
+
+ conn = psycopg.connect("postgresql://...")
+ PsycopgInstrumentor.instrument_connection(
+ conn,
+ capture_parameters=True, # Enable for this connection only
+ enable_sqlcommenter=True,
+ )
+ ```
+ """
+ # Get psycopg version
+ try:
+ version = importlib.metadata.version("psycopg")
+ except importlib.metadata.PackageNotFoundError:
+ version = "unknown"
+
+ pricing_info = kwargs.get("pricing_info", {})
+ metrics = kwargs.get("metrics_dict")
+ disable_metrics = kwargs.get("disable_metrics", False)
+
+ # Determine if this is an async connection
+ connection_class_name = connection.__class__.__name__
+ is_async = connection_class_name.startswith("Async")
+
+ # Get the appropriate wrappers
+ if is_async:
+ connection_wrappers = ASYNC_CONNECTION_WRAPPERS
+ cursor_wrappers = ASYNC_CURSOR_WRAPPERS
+ else:
+ connection_wrappers = SYNC_CONNECTION_WRAPPERS
+ cursor_wrappers = SYNC_CURSOR_WRAPPERS
+
+ # Wrap connection-level operations (commit, rollback)
+ for method_name, endpoint in CONNECTION_OPERATIONS:
+ wrapper_func = connection_wrappers.get(method_name)
+ if wrapper_func and hasattr(connection, method_name):
+ original_method = getattr(connection, method_name)
+ wrapped = wrapper_func(
+ endpoint,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters,
+ enable_sqlcommenter,
+ )
+
+ # Create a bound wrapper for this instance
+ def make_bound_wrapper(orig, wrap, conn, async_mode):
+ if async_mode:
+ @functools.wraps(orig)
+ async def bound_wrapper(*args, **kw):
+ return await wrap(orig, conn, args, kw)
+ return bound_wrapper
+ else:
+ @functools.wraps(orig)
+ def bound_wrapper(*args, **kw):
+ return wrap(orig, conn, args, kw)
+ return bound_wrapper
+
+ setattr(
+ connection,
+ method_name,
+ make_bound_wrapper(original_method, wrapped, connection, is_async),
+ )
+
+ # Wrap the cursor() method to return instrumented cursors
+ original_cursor = connection.cursor
+
+ def create_instrumented_cursor_wrapper():
+ """Creates a wrapper for the cursor() method that instruments returned cursors."""
+
+ if is_async:
+
+ @functools.wraps(original_cursor)
+ def instrumented_cursor(*args, **kw):
+ cursor = original_cursor(*args, **kw)
+ cls._instrument_cursor_instance(
+ cursor,
+ cursor_wrappers,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters,
+ enable_sqlcommenter,
+ is_async=True,
+ )
+ return cursor
+ else:
+
+ @functools.wraps(original_cursor)
+ def instrumented_cursor(*args, **kw):
+ cursor = original_cursor(*args, **kw)
+ cls._instrument_cursor_instance(
+ cursor,
+ cursor_wrappers,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters,
+ enable_sqlcommenter,
+ is_async=False,
+ )
+ return cursor
+
+ return instrumented_cursor
+
+ connection.cursor = create_instrumented_cursor_wrapper()
+
+ # Mark the connection as instrumented to avoid double instrumentation
+ connection._openlit_instrumented = True
+
+ return connection
+
+ @classmethod
+ def _instrument_cursor_instance(
+ cls,
+ cursor: Any,
+ cursor_wrappers: dict,
+ version: str,
+ environment: str,
+ application_name: str,
+ tracer: Optional[Any],
+ pricing_info: dict,
+ capture_message_content: bool,
+ metrics: Optional[Any],
+ disable_metrics: bool,
+ capture_parameters: bool,
+ enable_sqlcommenter: bool,
+ is_async: bool,
+ ):
+ """Instrument a cursor instance's methods."""
+
+ for method_name, endpoint in CURSOR_OPERATIONS:
+ wrapper_func = cursor_wrappers.get(method_name)
+ if wrapper_func and hasattr(cursor, method_name):
+ original_method = getattr(cursor, method_name)
+ wrapped = wrapper_func(
+ endpoint,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters,
+ enable_sqlcommenter,
+ )
+
+ # Create a bound wrapper for this cursor instance
+ def make_cursor_wrapper(orig, wrap, cur, async_mode):
+ if async_mode:
+ @functools.wraps(orig)
+ async def bound_wrapper(*args, **kw):
+ return await wrap(orig, cur, args, kw)
+ return bound_wrapper
+ else:
+ @functools.wraps(orig)
+ def bound_wrapper(*args, **kw):
+ return wrap(orig, cur, args, kw)
+ return bound_wrapper
+
+ setattr(
+ cursor,
+ method_name,
+ make_cursor_wrapper(original_method, wrapped, cursor, is_async),
+ )
+
+ def _uninstrument(self, **kwargs):
+ pass
diff --git a/sdk/python/src/openlit/instrumentation/psycopg/async_psycopg.py b/sdk/python/src/openlit/instrumentation/psycopg/async_psycopg.py
new file mode 100644
index 00000000..d8521ed5
--- /dev/null
+++ b/sdk/python/src/openlit/instrumentation/psycopg/async_psycopg.py
@@ -0,0 +1,586 @@
+# pylint: disable=duplicate-code, broad-exception-caught, too-many-statements, unused-argument, possibly-used-before-assignment, too-many-branches
+"""
+Module for monitoring Psycopg (PostgreSQL) async operations.
+"""
+
+import time
+from opentelemetry.trace import SpanKind
+from opentelemetry import context as context_api
+from openlit.__helpers import handle_exception
+from openlit.instrumentation.psycopg.utils import (
+ parse_sql_operation,
+ extract_table_name,
+ extract_connection_info,
+ extract_database_name,
+ process_cursor_response,
+ process_connection_response,
+ inject_sql_comment,
+)
+from openlit.semcov import SemanticConvention
+
+
+def async_execute_wrap(
+ gen_ai_endpoint,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters=False,
+ enable_sqlcommenter=False,
+):
+ """
+ Generates a telemetry wrapper for AsyncCursor.execute operations.
+
+ Args:
+ capture_parameters: If True, captures query parameters in spans (security risk!)
+ enable_sqlcommenter: If True, injects trace context as SQL comments
+ """
+
+ async def wrapper(wrapped, instance, args, kwargs):
+ """
+ Wraps the AsyncCursor.execute operation with tracing and logging.
+ """
+ # CRITICAL: Suppression check
+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):
+ return await wrapped(*args, **kwargs)
+
+ # Extract query and params from args/kwargs
+ query = args[0] if args else kwargs.get("query", "")
+ params = args[1] if len(args) > 1 else kwargs.get("params", None)
+
+ # Parse operation and table
+ db_operation = parse_sql_operation(query)
+ table_name = extract_table_name(query)
+
+ # Get connection from cursor
+ connection = getattr(instance, "connection", None)
+
+ # Server address calculation
+ server_address, server_port = extract_connection_info(connection)
+ database_name = extract_database_name(connection)
+
+ # Span naming: use operation + table
+ span_name = f"{db_operation} {table_name}"
+
+ # CRITICAL: Use tracer.start_as_current_span() for proper context
+ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
+ start_time = time.time()
+
+ # Inject SQLCommenter if enabled (must be done inside span context)
+ modified_query = inject_sql_comment(
+ query, application_name, enable_sqlcommenter
+ )
+ if modified_query != query:
+ args = (modified_query,) + args[1:] if args else args
+
+ response = await wrapped(*args, **kwargs)
+
+ try:
+ # Process response with endpoint information
+ response = process_cursor_response(
+ response,
+ db_operation,
+ table_name,
+ query, # Use original query for logging
+ server_address,
+ server_port,
+ database_name,
+ environment,
+ application_name,
+ metrics,
+ start_time,
+ span,
+ capture_message_content,
+ disable_metrics,
+ version,
+ cursor=instance,
+ connection=connection,
+ endpoint=gen_ai_endpoint,
+ capture_parameters=capture_parameters,
+ params=params,
+ )
+
+ except Exception as e:
+ handle_exception(span, e)
+
+ return response
+
+ return wrapper
+
+
+def async_executemany_wrap(
+ gen_ai_endpoint,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters=False,
+ enable_sqlcommenter=False,
+):
+ """
+ Generates a telemetry wrapper for AsyncCursor.executemany operations.
+
+ Note: For executemany, capture_parameters only captures first batch item
+ to avoid huge traces.
+ """
+
+ async def wrapper(wrapped, instance, args, kwargs):
+ """
+ Wraps the AsyncCursor.executemany operation with tracing and logging.
+ """
+ # CRITICAL: Suppression check
+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):
+ return await wrapped(*args, **kwargs)
+
+ # Extract query from args/kwargs
+ query = args[0] if args else kwargs.get("query", "")
+ params_seq = args[1] if len(args) > 1 else kwargs.get("params_seq", [])
+
+ # Parse operation and table
+ db_operation = parse_sql_operation(query)
+ table_name = extract_table_name(query)
+
+ # Get connection from cursor
+ connection = getattr(instance, "connection", None)
+
+ # Server address calculation
+ server_address, server_port = extract_connection_info(connection)
+ database_name = extract_database_name(connection)
+
+ # Span naming: use operation + table + batch indicator
+ params_list = list(params_seq) if params_seq else []
+ batch_size = len(params_list)
+ span_name = f"{db_operation} {table_name} (batch)"
+
+ # CRITICAL: Use tracer.start_as_current_span() for proper context
+ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
+ start_time = time.time()
+
+ # Inject SQLCommenter if enabled
+ modified_query = inject_sql_comment(
+ query, application_name, enable_sqlcommenter
+ )
+ if modified_query != query:
+ args = (modified_query,) + args[1:] if args else args
+
+ response = await wrapped(*args, **kwargs)
+
+ try:
+ # Add batch-specific attribute
+ span.set_attribute("db.batch.size", batch_size)
+
+ # For executemany, only capture first param set to avoid huge traces
+ first_params = params_list[0] if params_list else None
+
+ # Process response with endpoint information
+ response = process_cursor_response(
+ response,
+ db_operation,
+ table_name,
+ query,
+ server_address,
+ server_port,
+ database_name,
+ environment,
+ application_name,
+ metrics,
+ start_time,
+ span,
+ capture_message_content,
+ disable_metrics,
+ version,
+ cursor=instance,
+ connection=connection,
+ endpoint=gen_ai_endpoint,
+ capture_parameters=capture_parameters,
+ params=first_params,
+ )
+
+ except Exception as e:
+ handle_exception(span, e)
+
+ return response
+
+ return wrapper
+
+
+def async_copy_wrap(
+ gen_ai_endpoint,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters=False,
+ enable_sqlcommenter=False,
+):
+ """
+ Generates a telemetry wrapper for AsyncCursor.copy operations.
+
+ Note: COPY operations don't typically have parameters, so capture_parameters
+ has limited effect here. SQLCommenter is also not injected for COPY statements.
+ """
+
+ async def wrapper(wrapped, instance, args, kwargs):
+ """
+ Wraps the AsyncCursor.copy operation with tracing and logging.
+ """
+ # CRITICAL: Suppression check
+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):
+ return await wrapped(*args, **kwargs)
+
+ # Extract statement from args/kwargs
+ statement = args[0] if args else kwargs.get("statement", "")
+
+ # Parse operation and table
+ db_operation = SemanticConvention.DB_OPERATION_COPY
+ table_name = extract_table_name(statement)
+
+ # Get connection from cursor
+ connection = getattr(instance, "connection", None)
+
+ # Server address calculation
+ server_address, server_port = extract_connection_info(connection)
+ database_name = extract_database_name(connection)
+
+ # Span naming
+ span_name = f"{db_operation} {table_name}"
+
+ # CRITICAL: Use tracer.start_as_current_span() for proper context
+ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
+ start_time = time.time()
+ response = await wrapped(*args, **kwargs)
+
+ try:
+ # Process response with endpoint information
+ response = process_cursor_response(
+ response,
+ db_operation,
+ table_name,
+ statement,
+ server_address,
+ server_port,
+ database_name,
+ environment,
+ application_name,
+ metrics,
+ start_time,
+ span,
+ capture_message_content,
+ disable_metrics,
+ version,
+ cursor=instance,
+ connection=connection,
+ endpoint=gen_ai_endpoint,
+ )
+
+ except Exception as e:
+ handle_exception(span, e)
+
+ return response
+
+ return wrapper
+
+
+def async_commit_wrap(
+ gen_ai_endpoint,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters=False,
+ enable_sqlcommenter=False,
+):
+ """
+ Generates a telemetry wrapper for AsyncConnection.commit operations.
+
+ Note: capture_parameters and enable_sqlcommenter are accepted for API
+ consistency but not used for commit operations.
+ """
+
+ async def wrapper(wrapped, instance, args, kwargs):
+ """
+ Wraps the AsyncConnection.commit operation with tracing and logging.
+ """
+ # CRITICAL: Suppression check
+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):
+ return await wrapped(*args, **kwargs)
+
+ db_operation = SemanticConvention.DB_OPERATION_COMMIT
+
+ # Server address calculation
+ server_address, server_port = extract_connection_info(instance)
+ database_name = extract_database_name(instance)
+
+ # Span naming
+ span_name = f"{db_operation}"
+
+ # CRITICAL: Use tracer.start_as_current_span() for proper context
+ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
+ start_time = time.time()
+ response = await wrapped(*args, **kwargs)
+
+ try:
+ # Process response with endpoint information
+ response = process_connection_response(
+ response,
+ db_operation,
+ server_address,
+ server_port,
+ database_name,
+ environment,
+ application_name,
+ metrics,
+ start_time,
+ span,
+ capture_message_content,
+ disable_metrics,
+ version,
+ connection=instance,
+ endpoint=gen_ai_endpoint,
+ )
+
+ except Exception as e:
+ handle_exception(span, e)
+
+ return response
+
+ return wrapper
+
+
+def async_rollback_wrap(
+ gen_ai_endpoint,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters=False,
+ enable_sqlcommenter=False,
+):
+ """
+ Generates a telemetry wrapper for AsyncConnection.rollback operations.
+
+ Note: capture_parameters and enable_sqlcommenter are accepted for API
+ consistency but not used for rollback operations.
+ """
+
+ async def wrapper(wrapped, instance, args, kwargs):
+ """
+ Wraps the AsyncConnection.rollback operation with tracing and logging.
+ """
+ # CRITICAL: Suppression check
+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):
+ return await wrapped(*args, **kwargs)
+
+ db_operation = SemanticConvention.DB_OPERATION_ROLLBACK
+
+ # Server address calculation
+ server_address, server_port = extract_connection_info(instance)
+ database_name = extract_database_name(instance)
+
+ # Span naming
+ span_name = f"{db_operation}"
+
+ # CRITICAL: Use tracer.start_as_current_span() for proper context
+ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
+ start_time = time.time()
+ response = await wrapped(*args, **kwargs)
+
+ try:
+ # Process response with endpoint information
+ response = process_connection_response(
+ response,
+ db_operation,
+ server_address,
+ server_port,
+ database_name,
+ environment,
+ application_name,
+ metrics,
+ start_time,
+ span,
+ capture_message_content,
+ disable_metrics,
+ version,
+ connection=instance,
+ endpoint=gen_ai_endpoint,
+ )
+
+ except Exception as e:
+ handle_exception(span, e)
+
+ return response
+
+ return wrapper
+
+
+def async_callproc_wrap(
+ gen_ai_endpoint,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters=False,
+ enable_sqlcommenter=False,
+):
+ """
+ Generates a telemetry wrapper for AsyncCursor.callproc operations (stored procedures).
+
+ Note: enable_sqlcommenter is not applicable to callproc (procedure calls
+ don't use SQL strings). capture_parameters captures procedure arguments.
+ """
+
+ async def wrapper(wrapped, instance, args, kwargs):
+ """
+ Wraps the AsyncCursor.callproc operation with tracing and logging.
+ """
+ # CRITICAL: Suppression check
+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):
+ return await wrapped(*args, **kwargs)
+
+ # Extract procedure name and parameters from args
+ proc_name = args[0] if args else kwargs.get("procname", "unknown")
+ proc_params = args[1] if len(args) > 1 else kwargs.get("parameters", None)
+
+ # Parse operation
+ db_operation = SemanticConvention.DB_OPERATION_CALL
+
+ # Get connection from cursor
+ connection = getattr(instance, "connection", None)
+
+ # Server address calculation
+ server_address, server_port = extract_connection_info(connection)
+ database_name = extract_database_name(connection)
+
+ # Span naming: use CALL + procedure name
+ span_name = f"{db_operation} {proc_name}"
+
+ # CRITICAL: Use tracer.start_as_current_span() for proper context
+ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
+ start_time = time.time()
+ response = await wrapped(*args, **kwargs)
+
+ try:
+ # Process response with endpoint information
+ response = process_cursor_response(
+ response,
+ db_operation,
+ proc_name,
+ f"CALL {proc_name}",
+ server_address,
+ server_port,
+ database_name,
+ environment,
+ application_name,
+ metrics,
+ start_time,
+ span,
+ capture_message_content,
+ disable_metrics,
+ version,
+ cursor=instance,
+ connection=connection,
+ endpoint=gen_ai_endpoint,
+ capture_parameters=capture_parameters,
+ params=proc_params,
+ )
+
+ except Exception as e:
+ handle_exception(span, e)
+
+ return response
+
+ return wrapper
+
+
+def async_pool_getconn_wrap(
+ gen_ai_endpoint,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters=False,
+ enable_sqlcommenter=False,
+):
+ """
+ Generates a telemetry wrapper for AsyncConnectionPool.getconn operations.
+
+ Note: capture_parameters and enable_sqlcommenter are accepted for API
+ consistency but not used for pool operations.
+ """
+
+ async def wrapper(wrapped, instance, args, kwargs):
+ """
+ Wraps the AsyncConnectionPool.getconn operation with tracing and logging.
+ """
+ # CRITICAL: Suppression check
+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):
+ return await wrapped(*args, **kwargs)
+
+ db_operation = "pool.getconn"
+
+ # Span naming
+ span_name = "PostgreSQL pool.getconn"
+
+ # CRITICAL: Use tracer.start_as_current_span() for proper context
+ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
+ start_time = time.time()
+ response = await wrapped(*args, **kwargs)
+ end_time = time.time()
+
+ try:
+ # Set pool-specific attributes
+ span.set_attribute(
+ SemanticConvention.DB_SYSTEM_NAME,
+ SemanticConvention.DB_SYSTEM_POSTGRESQL,
+ )
+ span.set_attribute(SemanticConvention.DB_OPERATION_NAME, db_operation)
+ span.set_attribute(
+ SemanticConvention.DB_CLIENT_OPERATION_DURATION,
+ end_time - start_time,
+ )
+
+ # Try to get pool stats
+ if hasattr(instance, "get_stats"):
+ try:
+ stats = instance.get_stats()
+ span.set_attribute("db.pool.size", stats.get("pool_size", 0))
+ span.set_attribute(
+ "db.pool.available", stats.get("pool_available", 0)
+ )
+ except Exception:
+ pass
+
+ except Exception as e:
+ handle_exception(span, e)
+
+ return response
+
+ return wrapper
diff --git a/sdk/python/src/openlit/instrumentation/psycopg/psycopg.py b/sdk/python/src/openlit/instrumentation/psycopg/psycopg.py
new file mode 100644
index 00000000..1e2061c7
--- /dev/null
+++ b/sdk/python/src/openlit/instrumentation/psycopg/psycopg.py
@@ -0,0 +1,587 @@
+# pylint: disable=duplicate-code, broad-exception-caught, too-many-statements, unused-argument, possibly-used-before-assignment, too-many-branches
+"""
+Module for monitoring Psycopg (PostgreSQL) sync operations.
+"""
+
+import time
+from opentelemetry.trace import SpanKind
+from opentelemetry import context as context_api
+from openlit.__helpers import handle_exception
+from openlit.instrumentation.psycopg.utils import (
+ parse_sql_operation,
+ extract_table_name,
+ extract_connection_info,
+ extract_database_name,
+ process_cursor_response,
+ process_connection_response,
+ inject_sql_comment,
+)
+from openlit.semcov import SemanticConvention
+
+
+def execute_wrap(
+ gen_ai_endpoint,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters=False,
+ enable_sqlcommenter=False,
+):
+ """
+ Generates a telemetry wrapper for Cursor.execute operations.
+
+ Args:
+ capture_parameters: If True, captures query parameters in spans (security risk!)
+ enable_sqlcommenter: If True, injects trace context as SQL comments
+ """
+
+ def wrapper(wrapped, instance, args, kwargs):
+ """
+ Wraps the Cursor.execute operation with tracing and logging.
+ """
+ # CRITICAL: Suppression check
+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):
+ return wrapped(*args, **kwargs)
+
+ # Extract query and params from args/kwargs
+ query = args[0] if args else kwargs.get("query", "")
+ params = args[1] if len(args) > 1 else kwargs.get("params", None)
+
+ # Parse operation and table
+ db_operation = parse_sql_operation(query)
+ table_name = extract_table_name(query)
+
+ # Get connection from cursor
+ connection = getattr(instance, "connection", None)
+
+ # Server address calculation
+ server_address, server_port = extract_connection_info(connection)
+ database_name = extract_database_name(connection)
+
+ # Span naming: use operation + table
+ span_name = f"{db_operation} {table_name}"
+
+ # CRITICAL: Use tracer.start_as_current_span() for proper context
+ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
+ start_time = time.time()
+
+ # Inject SQLCommenter if enabled (must be done inside span context)
+ modified_query = inject_sql_comment(
+ query, application_name, enable_sqlcommenter
+ )
+ if modified_query != query:
+ # Update args with modified query
+ args = (modified_query,) + args[1:] if args else args
+
+ response = wrapped(*args, **kwargs)
+
+ try:
+ # Process response with endpoint information
+ response = process_cursor_response(
+ response,
+ db_operation,
+ table_name,
+ query, # Use original query for logging
+ server_address,
+ server_port,
+ database_name,
+ environment,
+ application_name,
+ metrics,
+ start_time,
+ span,
+ capture_message_content,
+ disable_metrics,
+ version,
+ cursor=instance,
+ connection=connection,
+ endpoint=gen_ai_endpoint,
+ capture_parameters=capture_parameters,
+ params=params,
+ )
+
+ except Exception as e:
+ handle_exception(span, e)
+
+ return response
+
+ return wrapper
+
+
+def executemany_wrap(
+ gen_ai_endpoint,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters=False,
+ enable_sqlcommenter=False,
+):
+ """
+ Generates a telemetry wrapper for Cursor.executemany operations.
+
+ Note: For executemany, capture_parameters only captures first batch item
+ to avoid huge traces.
+ """
+
+ def wrapper(wrapped, instance, args, kwargs):
+ """
+ Wraps the Cursor.executemany operation with tracing and logging.
+ """
+ # CRITICAL: Suppression check
+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):
+ return wrapped(*args, **kwargs)
+
+ # Extract query from args/kwargs
+ query = args[0] if args else kwargs.get("query", "")
+ params_seq = args[1] if len(args) > 1 else kwargs.get("params_seq", [])
+
+ # Parse operation and table
+ db_operation = parse_sql_operation(query)
+ table_name = extract_table_name(query)
+
+ # Get connection from cursor
+ connection = getattr(instance, "connection", None)
+
+ # Server address calculation
+ server_address, server_port = extract_connection_info(connection)
+ database_name = extract_database_name(connection)
+
+ # Span naming: use operation + table + batch indicator
+ params_list = list(params_seq) if params_seq else []
+ batch_size = len(params_list)
+ span_name = f"{db_operation} {table_name} (batch)"
+
+ # CRITICAL: Use tracer.start_as_current_span() for proper context
+ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
+ start_time = time.time()
+
+ # Inject SQLCommenter if enabled
+ modified_query = inject_sql_comment(
+ query, application_name, enable_sqlcommenter
+ )
+ if modified_query != query:
+ args = (modified_query,) + args[1:] if args else args
+
+ response = wrapped(*args, **kwargs)
+
+ try:
+ # Add batch-specific attribute
+ span.set_attribute("db.batch.size", batch_size)
+
+ # For executemany, only capture first param set to avoid huge traces
+ first_params = params_list[0] if params_list else None
+
+ # Process response with endpoint information
+ response = process_cursor_response(
+ response,
+ db_operation,
+ table_name,
+ query,
+ server_address,
+ server_port,
+ database_name,
+ environment,
+ application_name,
+ metrics,
+ start_time,
+ span,
+ capture_message_content,
+ disable_metrics,
+ version,
+ cursor=instance,
+ connection=connection,
+ endpoint=gen_ai_endpoint,
+ capture_parameters=capture_parameters,
+ params=first_params,
+ )
+
+ except Exception as e:
+ handle_exception(span, e)
+
+ return response
+
+ return wrapper
+
+
+def copy_wrap(
+ gen_ai_endpoint,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters=False,
+ enable_sqlcommenter=False,
+):
+ """
+ Generates a telemetry wrapper for Cursor.copy operations.
+
+ Note: COPY operations don't typically have parameters, so capture_parameters
+ has limited effect here. SQLCommenter is also not injected for COPY statements.
+ """
+
+ def wrapper(wrapped, instance, args, kwargs):
+ """
+ Wraps the Cursor.copy operation with tracing and logging.
+ """
+ # CRITICAL: Suppression check
+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):
+ return wrapped(*args, **kwargs)
+
+ # Extract statement from args/kwargs
+ statement = args[0] if args else kwargs.get("statement", "")
+
+ # Parse operation and table
+ db_operation = SemanticConvention.DB_OPERATION_COPY
+ table_name = extract_table_name(statement)
+
+ # Get connection from cursor
+ connection = getattr(instance, "connection", None)
+
+ # Server address calculation
+ server_address, server_port = extract_connection_info(connection)
+ database_name = extract_database_name(connection)
+
+ # Span naming
+ span_name = f"{db_operation} {table_name}"
+
+ # CRITICAL: Use tracer.start_as_current_span() for proper context
+ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
+ start_time = time.time()
+ response = wrapped(*args, **kwargs)
+
+ try:
+ # Process response with endpoint information
+ response = process_cursor_response(
+ response,
+ db_operation,
+ table_name,
+ statement,
+ server_address,
+ server_port,
+ database_name,
+ environment,
+ application_name,
+ metrics,
+ start_time,
+ span,
+ capture_message_content,
+ disable_metrics,
+ version,
+ cursor=instance,
+ connection=connection,
+ endpoint=gen_ai_endpoint,
+ )
+
+ except Exception as e:
+ handle_exception(span, e)
+
+ return response
+
+ return wrapper
+
+
+def commit_wrap(
+ gen_ai_endpoint,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters=False,
+ enable_sqlcommenter=False,
+):
+ """
+ Generates a telemetry wrapper for Connection.commit operations.
+
+ Note: capture_parameters and enable_sqlcommenter are accepted for API
+ consistency but not used for commit operations.
+ """
+
+ def wrapper(wrapped, instance, args, kwargs):
+ """
+ Wraps the Connection.commit operation with tracing and logging.
+ """
+ # CRITICAL: Suppression check
+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):
+ return wrapped(*args, **kwargs)
+
+ db_operation = SemanticConvention.DB_OPERATION_COMMIT
+
+ # Server address calculation
+ server_address, server_port = extract_connection_info(instance)
+ database_name = extract_database_name(instance)
+
+ # Span naming
+ span_name = f"{db_operation}"
+
+ # CRITICAL: Use tracer.start_as_current_span() for proper context
+ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
+ start_time = time.time()
+ response = wrapped(*args, **kwargs)
+
+ try:
+ # Process response with endpoint information
+ response = process_connection_response(
+ response,
+ db_operation,
+ server_address,
+ server_port,
+ database_name,
+ environment,
+ application_name,
+ metrics,
+ start_time,
+ span,
+ capture_message_content,
+ disable_metrics,
+ version,
+ connection=instance,
+ endpoint=gen_ai_endpoint,
+ )
+
+ except Exception as e:
+ handle_exception(span, e)
+
+ return response
+
+ return wrapper
+
+
+def rollback_wrap(
+ gen_ai_endpoint,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters=False,
+ enable_sqlcommenter=False,
+):
+ """
+ Generates a telemetry wrapper for Connection.rollback operations.
+
+ Note: capture_parameters and enable_sqlcommenter are accepted for API
+ consistency but not used for rollback operations.
+ """
+
+ def wrapper(wrapped, instance, args, kwargs):
+ """
+ Wraps the Connection.rollback operation with tracing and logging.
+ """
+ # CRITICAL: Suppression check
+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):
+ return wrapped(*args, **kwargs)
+
+ db_operation = SemanticConvention.DB_OPERATION_ROLLBACK
+
+ # Server address calculation
+ server_address, server_port = extract_connection_info(instance)
+ database_name = extract_database_name(instance)
+
+ # Span naming
+ span_name = f"{db_operation}"
+
+ # CRITICAL: Use tracer.start_as_current_span() for proper context
+ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
+ start_time = time.time()
+ response = wrapped(*args, **kwargs)
+
+ try:
+ # Process response with endpoint information
+ response = process_connection_response(
+ response,
+ db_operation,
+ server_address,
+ server_port,
+ database_name,
+ environment,
+ application_name,
+ metrics,
+ start_time,
+ span,
+ capture_message_content,
+ disable_metrics,
+ version,
+ connection=instance,
+ endpoint=gen_ai_endpoint,
+ )
+
+ except Exception as e:
+ handle_exception(span, e)
+
+ return response
+
+ return wrapper
+
+
+def callproc_wrap(
+ gen_ai_endpoint,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters=False,
+ enable_sqlcommenter=False,
+):
+ """
+ Generates a telemetry wrapper for Cursor.callproc operations (stored procedures).
+
+ Note: enable_sqlcommenter is not applicable to callproc (procedure calls
+ don't use SQL strings). capture_parameters captures procedure arguments.
+ """
+
+ def wrapper(wrapped, instance, args, kwargs):
+ """
+ Wraps the Cursor.callproc operation with tracing and logging.
+ """
+ # CRITICAL: Suppression check
+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):
+ return wrapped(*args, **kwargs)
+
+ # Extract procedure name and parameters from args
+ proc_name = args[0] if args else kwargs.get("procname", "unknown")
+ proc_params = args[1] if len(args) > 1 else kwargs.get("parameters", None)
+
+ # Parse operation
+ db_operation = SemanticConvention.DB_OPERATION_CALL
+
+ # Get connection from cursor
+ connection = getattr(instance, "connection", None)
+
+ # Server address calculation
+ server_address, server_port = extract_connection_info(connection)
+ database_name = extract_database_name(connection)
+
+ # Span naming: use CALL + procedure name
+ span_name = f"{db_operation} {proc_name}"
+
+ # CRITICAL: Use tracer.start_as_current_span() for proper context
+ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
+ start_time = time.time()
+ response = wrapped(*args, **kwargs)
+
+ try:
+ # Process response with endpoint information
+ response = process_cursor_response(
+ response,
+ db_operation,
+ proc_name,
+ f"CALL {proc_name}",
+ server_address,
+ server_port,
+ database_name,
+ environment,
+ application_name,
+ metrics,
+ start_time,
+ span,
+ capture_message_content,
+ disable_metrics,
+ version,
+ cursor=instance,
+ connection=connection,
+ endpoint=gen_ai_endpoint,
+ capture_parameters=capture_parameters,
+ params=proc_params,
+ )
+
+ except Exception as e:
+ handle_exception(span, e)
+
+ return response
+
+ return wrapper
+
+
+def pool_getconn_wrap(
+ gen_ai_endpoint,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ capture_parameters=False,
+ enable_sqlcommenter=False,
+):
+ """
+ Generates a telemetry wrapper for ConnectionPool.getconn operations.
+
+ Note: capture_parameters and enable_sqlcommenter are accepted for API
+ consistency but not used for pool operations.
+ """
+
+ def wrapper(wrapped, instance, args, kwargs):
+ """
+ Wraps the ConnectionPool.getconn operation with tracing and logging.
+ """
+ # CRITICAL: Suppression check
+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):
+ return wrapped(*args, **kwargs)
+
+ db_operation = "pool.getconn"
+
+ # Span naming
+ span_name = "PostgreSQL pool.getconn"
+
+ # CRITICAL: Use tracer.start_as_current_span() for proper context
+ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
+ start_time = time.time()
+ response = wrapped(*args, **kwargs)
+ end_time = time.time()
+
+ try:
+ # Set pool-specific attributes
+ span.set_attribute(
+ SemanticConvention.DB_SYSTEM_NAME,
+ SemanticConvention.DB_SYSTEM_POSTGRESQL,
+ )
+ span.set_attribute(SemanticConvention.DB_OPERATION_NAME, db_operation)
+ span.set_attribute(
+ SemanticConvention.DB_CLIENT_OPERATION_DURATION,
+ end_time - start_time,
+ )
+
+ # Try to get pool stats
+ if hasattr(instance, "get_stats"):
+ try:
+ stats = instance.get_stats()
+ span.set_attribute("db.pool.size", stats.get("pool_size", 0))
+ span.set_attribute(
+ "db.pool.available", stats.get("pool_available", 0)
+ )
+ except Exception:
+ pass
+
+ except Exception as e:
+ handle_exception(span, e)
+
+ return response
+
+ return wrapper
diff --git a/sdk/python/src/openlit/instrumentation/psycopg/utils.py b/sdk/python/src/openlit/instrumentation/psycopg/utils.py
new file mode 100644
index 00000000..f3cdfdb8
--- /dev/null
+++ b/sdk/python/src/openlit/instrumentation/psycopg/utils.py
@@ -0,0 +1,684 @@
+"""
+Utilities for Psycopg (PostgreSQL) instrumentation.
+"""
+
+import re
+import time
+from typing import Tuple, Any, Optional
+from opentelemetry.trace import Status, StatusCode, get_current_span
+from openlit.__helpers import (
+ common_db_span_attributes,
+ record_db_metrics,
+)
+from openlit.semcov import SemanticConvention
+
+# Maximum parameter value length to capture (to avoid huge traces)
+MAX_PARAM_LENGTH = 256
+# Maximum number of parameters to capture
+MAX_PARAMS_COUNT = 50
+
+# Operation mapping for SQL statements
+SQL_OPERATION_MAP = {
+ "SELECT": SemanticConvention.DB_OPERATION_SELECT,
+ "INSERT": SemanticConvention.DB_OPERATION_INSERT,
+ "UPDATE": SemanticConvention.DB_OPERATION_UPDATE,
+ "DELETE": SemanticConvention.DB_OPERATION_DELETE,
+ "COPY": SemanticConvention.DB_OPERATION_COPY,
+ "CREATE": SemanticConvention.DB_OPERATION_CREATE,
+ "ALTER": SemanticConvention.DB_OPERATION_ALTER,
+ "DROP": SemanticConvention.DB_OPERATION_DROP,
+ "TRUNCATE": SemanticConvention.DB_OPERATION_TRUNCATE,
+ "COMMIT": SemanticConvention.DB_OPERATION_COMMIT,
+ "ROLLBACK": SemanticConvention.DB_OPERATION_ROLLBACK,
+}
+
+# Patterns for extracting table names from SQL queries
+TABLE_PATTERNS = [
+ r'INSERT\s+INTO\s+["\']?(\w+)["\']?',
+ r'UPDATE\s+["\']?(\w+)["\']?',
+ r'DELETE\s+FROM\s+["\']?(\w+)["\']?',
+ r'FROM\s+["\']?(\w+)["\']?',
+ r'TRUNCATE\s+(?:TABLE\s+)?["\']?(\w+)["\']?',
+ r'CREATE\s+(?:TABLE|INDEX)\s+(?:IF\s+NOT\s+EXISTS\s+)?["\']?(\w+)["\']?',
+ r'ALTER\s+TABLE\s+["\']?(\w+)["\']?',
+ r'DROP\s+(?:TABLE|INDEX)\s+(?:IF\s+EXISTS\s+)?["\']?(\w+)["\']?',
+ r'COPY\s+["\']?(\w+)["\']?',
+]
+
+
+def parse_sql_operation(query: Any) -> str:
+ """
+ Parse SQL statement to detect operation type.
+
+ Args:
+ query: SQL query string or SQL composition object
+
+ Returns:
+ Operation type constant from SemanticConvention
+ """
+ if query is None:
+ return SemanticConvention.DB_OPERATION_QUERY
+
+ # Handle psycopg sql.SQL and sql.Composed objects
+ query_str = str(query).strip()
+ if not query_str:
+ return SemanticConvention.DB_OPERATION_QUERY
+
+ # Get the first word (SQL command)
+ query_upper = query_str.upper()
+
+ # Check for common SQL operations
+ for keyword, operation in SQL_OPERATION_MAP.items():
+ if query_upper.startswith(keyword):
+ return operation
+
+ # Handle WITH ... SELECT/INSERT/UPDATE/DELETE (CTEs)
+ if query_upper.startswith("WITH"):
+ # Look for the actual operation after the CTE
+ for keyword, operation in SQL_OPERATION_MAP.items():
+ if keyword in query_upper:
+ return operation
+
+ return SemanticConvention.DB_OPERATION_QUERY
+
+
+def extract_table_name(query: Any) -> str:
+ """
+ Extract table name from SQL query for span naming.
+
+ Args:
+ query: SQL query string or SQL composition object
+
+ Returns:
+ Table name or "unknown" if not found
+ """
+ if query is None:
+ return "unknown"
+
+ query_str = str(query)
+
+ for pattern in TABLE_PATTERNS:
+ match = re.search(pattern, query_str, re.IGNORECASE)
+ if match:
+ return match.group(1)
+
+ return "unknown"
+
+
+def extract_connection_info(connection: Any) -> Tuple[str, int]:
+ """
+ Extract server address and port from psycopg connection.
+
+ Args:
+ connection: Psycopg Connection or AsyncConnection object
+
+ Returns:
+ Tuple of (server_address, server_port)
+ """
+ default_address = "localhost"
+ default_port = 5432
+
+ try:
+ if hasattr(connection, "info"):
+ info = connection.info
+ host = getattr(info, "host", None) or default_address
+ port = getattr(info, "port", None) or default_port
+ return host, int(port)
+ except Exception:
+ pass
+
+ return default_address, default_port
+
+
+def extract_database_name(connection: Any) -> str:
+ """
+ Extract database name from psycopg connection.
+
+ Args:
+ connection: Psycopg Connection or AsyncConnection object
+
+ Returns:
+ Database name or "unknown"
+ """
+ try:
+ if hasattr(connection, "info"):
+ return getattr(connection.info, "dbname", None) or "unknown"
+ except Exception:
+ pass
+
+ return "unknown"
+
+
+def detect_special_features(query: Any) -> dict:
+ """
+ Detect special PostgreSQL features in the query.
+
+ Args:
+ query: SQL query string
+
+ Returns:
+ Dict with detected features
+ """
+ features = {}
+ if query is None:
+ return features
+
+ query_str = str(query).upper()
+
+ # pgvector similarity operators
+ if "<=>" in str(query):
+ features["similarity_metric"] = "cosine"
+ elif "<->" in str(query):
+ features["similarity_metric"] = "l2"
+ elif "<#>" in str(query):
+ features["similarity_metric"] = "inner_product"
+
+ # Full-text search
+ if "TSVECTOR" in query_str or "TSQUERY" in query_str:
+ features["full_text_search"] = True
+ if "WEBSEARCH_TO_TSQUERY" in query_str:
+ features["websearch"] = True
+ if "TS_RANK" in query_str:
+ features["text_ranking"] = True
+
+ return features
+
+
+def get_query_summary(db_operation: str, table_name: str, query: Any) -> str:
+ """
+ Generate a human-readable query summary.
+
+ Args:
+ db_operation: The detected database operation
+ table_name: The table name
+ query: The SQL query
+
+ Returns:
+ Human-readable summary string
+ """
+ summary = f"{db_operation} {table_name}"
+
+ features = detect_special_features(query)
+ if features.get("similarity_metric"):
+ summary += f" (vector {features['similarity_metric']})"
+ if features.get("full_text_search"):
+ summary += " (full-text)"
+
+ return summary
+
+
+def sanitize_parameter(value: Any, max_length: int = MAX_PARAM_LENGTH) -> str:
+ """
+ Sanitize a parameter value for safe inclusion in traces.
+
+ Truncates long values and converts to string representation.
+ Does NOT mask sensitive data - that's the user's responsibility
+ to not enable capture_parameters with sensitive queries.
+
+ Args:
+ value: Parameter value
+ max_length: Maximum string length
+
+ Returns:
+ Sanitized string representation
+ """
+ if value is None:
+ return "NULL"
+
+ # Handle bytes (don't capture binary data)
+ if isinstance(value, (bytes, bytearray)):
+ return f"<bytes:{len(value)}>"
+
+ # Handle memoryview
+ if isinstance(value, memoryview):
+ return f"<memoryview:{len(value)}>"
+
+ # Convert to string
+ try:
+ str_value = str(value)
+ except Exception:
+ return "<unrepresentable>"
+
+ # Truncate if too long
+ if len(str_value) > max_length:
+ return str_value[:max_length] + f"...<truncated:{len(str_value)}>"
+
+ return str_value
+
+
+def format_parameters(
+ params: Any,
+ max_count: int = MAX_PARAMS_COUNT,
+ max_length: int = MAX_PARAM_LENGTH,
+) -> Optional[str]:
+ """
+ Format query parameters for span attributes.
+
+ Args:
+ params: Query parameters (tuple, list, dict, or None)
+ max_count: Maximum number of parameters to include
+ max_length: Maximum length per parameter value
+
+ Returns:
+ Formatted string or None if no parameters
+ """
+ if params is None:
+ return None
+
+ try:
+ if isinstance(params, dict):
+ # Named parameters: {"name": "value", ...}
+ items = list(params.items())[:max_count]
+ formatted = {k: sanitize_parameter(v, max_length) for k, v in items}
+ if len(params) > max_count:
+ formatted["..."] = f"<{len(params) - max_count} more>"
+ return str(formatted)
+
+ elif isinstance(params, (list, tuple)):
+ # Positional parameters: ($1, $2, ...)
+ items = list(params)[:max_count]
+ formatted = [sanitize_parameter(v, max_length) for v in items]
+ if len(params) > max_count:
+ formatted.append(f"<{len(params) - max_count} more>")
+ return str(formatted)
+
+ else:
+ # Single parameter
+ return sanitize_parameter(params, max_length)
+
+ except Exception:
+ return "<error formatting parameters>"
+
+
+def generate_sql_comment(
+ traceparent: Optional[str] = None,
+ tracestate: Optional[str] = None,
+ application_name: Optional[str] = None,
+) -> str:
+ """
+ Generate a SQL comment with trace context (SQLCommenter format).
+
+ This allows database logs to be correlated with application traces.
+ Format follows the SQLCommenter specification:
+ https://google.github.io/sqlcommenter/
+
+ Args:
+ traceparent: W3C Trace Context traceparent header value
+ tracestate: W3C Trace Context tracestate header value
+ application_name: Application name to include
+
+ Returns:
+ SQL comment string to append to queries
+ """
+ parts = []
+
+ if traceparent:
+ # URL-encode single quotes for safety
+ parts.append(f"traceparent='{traceparent}'")
+
+ if tracestate:
+ parts.append(f"tracestate='{tracestate}'")
+
+ if application_name:
+ # Sanitize application name (alphanumeric and underscores only)
+ safe_name = re.sub(r"[^a-zA-Z0-9_]", "_", application_name)
+ parts.append(f"application='{safe_name}'")
+
+ if not parts:
+ return ""
+
+ return "/*" + ",".join(parts) + "*/"
+
+
+def get_trace_context_for_comment() -> Tuple[Optional[str], Optional[str]]:
+ """
+ Extract current trace context for SQLCommenter.
+
+ Returns:
+ Tuple of (traceparent, tracestate) or (None, None) if no active span
+ """
+ try:
+ span = get_current_span()
+ if span is None or not span.is_recording():
+ return None, None
+
+ ctx = span.get_span_context()
+ if ctx is None or not ctx.is_valid:
+ return None, None
+
+ # Format traceparent: version-trace_id-span_id-flags
+ # Version is always 00
+ trace_id = format(ctx.trace_id, "032x")
+ span_id = format(ctx.span_id, "016x")
+ flags = format(ctx.trace_flags, "02x")
+ traceparent = f"00-{trace_id}-{span_id}-{flags}"
+
+ # Get tracestate if available
+ tracestate = None
+ if ctx.trace_state:
+ # Convert trace state to string
+ tracestate_items = []
+ for key, value in ctx.trace_state.items():
+ tracestate_items.append(f"{key}={value}")
+ if tracestate_items:
+ tracestate = ",".join(tracestate_items)
+
+ return traceparent, tracestate
+
+ except Exception:
+ return None, None
+
+
+def inject_sql_comment(
+ query: Any,
+ application_name: Optional[str] = None,
+ enable_sqlcommenter: bool = False,
+) -> Any:
+ """
+ Inject SQLCommenter trace context into a SQL query.
+
+ Only modifies string queries. SQL composition objects are returned as-is.
+ Only injects if enable_sqlcommenter is True.
+
+ Args:
+ query: Original SQL query
+ application_name: Application name to include in comment
+ enable_sqlcommenter: Whether SQLCommenter is enabled
+
+ Returns:
+ Modified query with comment appended, or original query
+ """
+ if not enable_sqlcommenter:
+ return query
+
+ # Only inject into string queries
+ if not isinstance(query, str):
+ return query
+
+ # Don't inject if query already has a comment at the end
+ stripped = query.rstrip()
+ if stripped.endswith("*/"):
+ return query
+
+ # Get current trace context
+ traceparent, tracestate = get_trace_context_for_comment()
+
+ # Generate comment
+ comment = generate_sql_comment(traceparent, tracestate, application_name)
+
+ if not comment:
+ return query
+
+ # Append comment to query
+ # Handle queries that end with semicolon
+ if stripped.endswith(";"):
+ return stripped[:-1] + " " + comment + ";"
+ else:
+ return query + " " + comment
+
+
+def common_psycopg_logic(
+ scope,
+ environment,
+ application_name,
+ metrics,
+ capture_message_content,
+ disable_metrics,
+ version,
+ connection=None,
+ endpoint=None,
+ capture_parameters=False,
+ params=None,
+):
+ """
+ Process psycopg request and generate telemetry.
+
+ Args:
+ scope: Scope object with span and operation data
+ environment: Deployment environment
+ application_name: Application name
+ metrics: Metrics dictionary
+ capture_message_content: Whether to capture query text
+ disable_metrics: Whether metrics are disabled
+ version: SDK version
+ connection: Database connection object
+ endpoint: API endpoint name
+ capture_parameters: Whether to capture query parameters
+ params: Query parameters (if capture_parameters is True)
+ """
+ scope._end_time = time.time()
+
+ # Set common database span attributes using helper
+ common_db_span_attributes(
+ scope,
+ SemanticConvention.DB_SYSTEM_POSTGRESQL,
+ scope._server_address,
+ scope._server_port,
+ environment,
+ application_name,
+ version,
+ )
+
+ # Set DB operation specific attributes
+ scope._span.set_attribute(SemanticConvention.DB_OPERATION_NAME, scope._db_operation)
+ scope._span.set_attribute(
+ SemanticConvention.DB_CLIENT_OPERATION_DURATION,
+ scope._end_time - scope._start_time,
+ )
+
+ # Set database namespace (database name)
+ if scope._database_name and scope._database_name != "unknown":
+ scope._span.set_attribute(SemanticConvention.DB_NAMESPACE, scope._database_name)
+
+ # Set table/collection name
+ if scope._table_name and scope._table_name != "unknown":
+ scope._span.set_attribute(
+ SemanticConvention.DB_COLLECTION_NAME, scope._table_name
+ )
+
+ # Set query text if capture is enabled
+ if capture_message_content and scope._query:
+ query_str = str(scope._query)
+ # Truncate very long queries
+ if len(query_str) > 4096:
+ query_str = query_str[:4096] + "..."
+ scope._span.set_attribute(SemanticConvention.DB_QUERY_TEXT, query_str)
+
+ # Set query parameters if capture is enabled
+ if capture_parameters and params is not None:
+ formatted_params = format_parameters(params)
+ if formatted_params:
+ scope._span.set_attribute(
+ SemanticConvention.DB_QUERY_PARAMETER, formatted_params
+ )
+
+ # Set query summary
+ scope._span.set_attribute(
+ SemanticConvention.DB_QUERY_SUMMARY,
+ get_query_summary(scope._db_operation, scope._table_name, scope._query),
+ )
+
+ # Set row count if available
+ if (
+ hasattr(scope, "_rowcount")
+ and scope._rowcount is not None
+ and scope._rowcount >= 0
+ ):
+ scope._span.set_attribute(
+ SemanticConvention.DB_RESPONSE_RETURNED_ROWS, scope._rowcount
+ )
+
+ # Set special features
+ features = detect_special_features(scope._query)
+ if features.get("similarity_metric"):
+ scope._span.set_attribute(
+ SemanticConvention.DB_SEARCH_SIMILARITY_METRIC,
+ features["similarity_metric"],
+ )
+
+ scope._span.set_status(Status(StatusCode.OK))
+
+ # Record metrics using helper
+ if not disable_metrics:
+ record_db_metrics(
+ metrics,
+ SemanticConvention.DB_SYSTEM_POSTGRESQL,
+ scope._server_address,
+ scope._server_port,
+ environment,
+ application_name,
+ scope._start_time,
+ scope._end_time,
+ scope._db_operation,
+ )
+
+
+def process_cursor_response(
+ response,
+ db_operation,
+ table_name,
+ query,
+ server_address,
+ server_port,
+ database_name,
+ environment,
+ application_name,
+ metrics,
+ start_time,
+ span,
+ capture_message_content,
+ disable_metrics,
+ version,
+ cursor=None,
+ connection=None,
+ endpoint=None,
+ capture_parameters=False,
+ params=None,
+):
+ """
+ Process psycopg cursor response and generate telemetry.
+
+ Args:
+ response: The cursor response
+ db_operation: Database operation type
+ table_name: Table name
+ query: SQL query
+ server_address: PostgreSQL server address
+ server_port: PostgreSQL server port
+ database_name: Database name
+ environment: Deployment environment
+ application_name: Application name
+ metrics: Metrics dictionary
+ start_time: Operation start time
+ span: OpenTelemetry span
+ capture_message_content: Whether to capture query text
+ disable_metrics: Whether metrics are disabled
+ version: SDK version
+ cursor: Cursor object
+ connection: Connection object
+ endpoint: API endpoint name
+ capture_parameters: Whether to capture query parameters
+ params: Query parameters (tuple, list, dict, or None)
+ """
+ # Create scope object
+ scope = type("GenericScope", (), {})()
+ scope._span = span
+ scope._response = response
+ scope._db_operation = db_operation
+ scope._table_name = table_name
+ scope._query = query
+ scope._server_address = server_address
+ scope._server_port = server_port
+ scope._database_name = database_name
+ scope._start_time = start_time
+
+ # Try to get rowcount from cursor
+ scope._rowcount = None
+ if cursor is not None:
+ try:
+ scope._rowcount = cursor.rowcount
+ except Exception:
+ pass
+
+ # Process the response
+ common_psycopg_logic(
+ scope,
+ environment,
+ application_name,
+ metrics,
+ capture_message_content,
+ disable_metrics,
+ version,
+ connection=connection,
+ endpoint=endpoint,
+ capture_parameters=capture_parameters,
+ params=params,
+ )
+
+ return response
+
+
+def process_connection_response(
+ response,
+ db_operation,
+ server_address,
+ server_port,
+ database_name,
+ environment,
+ application_name,
+ metrics,
+ start_time,
+ span,
+ capture_message_content,
+ disable_metrics,
+ version,
+ connection=None,
+ endpoint=None,
+):
+ """
+ Process psycopg connection response (commit/rollback) and generate telemetry.
+
+ Args:
+ response: The response
+ db_operation: Database operation type (COMMIT/ROLLBACK)
+ server_address: PostgreSQL server address
+ server_port: PostgreSQL server port
+ database_name: Database name
+ environment: Deployment environment
+ application_name: Application name
+ metrics: Metrics dictionary
+ start_time: Operation start time
+ span: OpenTelemetry span
+ capture_message_content: Whether to capture query text
+ disable_metrics: Whether metrics are disabled
+ version: SDK version
+ connection: Connection object
+ endpoint: API endpoint name
+ """
+ # Create scope object
+ scope = type("GenericScope", (), {})()
+ scope._span = span
+ scope._response = response
+ scope._db_operation = db_operation
+ scope._table_name = "transaction"
+ scope._query = db_operation
+ scope._server_address = server_address
+ scope._server_port = server_port
+ scope._database_name = database_name
+ scope._start_time = start_time
+ scope._rowcount = None
+
+ # Process the response
+ common_psycopg_logic(
+ scope,
+ environment,
+ application_name,
+ metrics,
+ capture_message_content,
+ disable_metrics,
+ version,
+ connection=connection,
+ endpoint=endpoint,
+ )
+
+ return response
diff --git a/sdk/python/src/openlit/semcov/__init__.py b/sdk/python/src/openlit/semcov/__init__.py
index 6aff949c..b3687f5a 100644
--- a/sdk/python/src/openlit/semcov/__init__.py
+++ b/sdk/python/src/openlit/semcov/__init__.py
@@ -399,6 +399,7 @@ class SemanticConvention:
DB_OPERATION_NAME = "db.operation.name"
DB_QUERY_TEXT = "db.query.text"
DB_QUERY_SUMMARY = "db.query.summary"
+ DB_QUERY_PARAMETER = "db.query.parameter"
DB_RESPONSE_RETURNED_ROWS = "db.response.returned_rows"
# Vector DB Attributes (Extras)
@@ -460,6 +461,21 @@ class SemanticConvention:
DB_SYSTEM_QDRANT = "qdrant"
DB_SYSTEM_MILVUS = "milvus"
DB_SYSTEM_ASTRA = "astra"
+ DB_SYSTEM_POSTGRESQL = "postgresql"
+
+ # SQL Transaction Operations
+ DB_OPERATION_COMMIT = "COMMIT"
+ DB_OPERATION_ROLLBACK = "ROLLBACK"
+ DB_OPERATION_COPY = "COPY"
+ DB_OPERATION_CREATE = "CREATE"
+ DB_OPERATION_ALTER = "ALTER"
+ DB_OPERATION_DROP = "DROP"
+ DB_OPERATION_TRUNCATE = "TRUNCATE"
+ DB_OPERATION_CALL = "CALL"
+
+ # PostgreSQL-specific attributes
+ DB_POSTGRESQL_ROWS_AFFECTED = "db.postgresql.rows_affected"
+ DB_POSTGRESQL_PLAN = "db.postgresql.plan"
# GenAI Request Attributes (OTel Semconv)
GEN_AI_AGENT_ID = "gen_ai.agent.id"