|
11 | 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 | 12 | # See the License for the specific language governing permissions and
|
13 | 13 | # limitations under the License.
|
| 14 | +import os |
14 | 15 |
|
15 | 16 | from sqlalchemy.event import listen # pylint: disable=no-name-in-module
|
16 | 17 |
|
17 | 18 | from opentelemetry import trace
|
18 | 19 | from opentelemetry.instrumentation.sqlalchemy.version import __version__
|
19 |
| -from opentelemetry.semconv.trace import SpanAttributes |
| 20 | +from opentelemetry.semconv.trace import NetTransportValues, SpanAttributes |
20 | 21 | from opentelemetry.trace.status import Status, StatusCode
|
21 | 22 |
|
22 | 23 |
|
@@ -157,14 +158,25 @@ def _get_attributes_from_url(url):
|
157 | 158 | def _get_attributes_from_cursor(vendor, cursor, attrs):
|
158 | 159 | """Attempt to set db connection attributes by introspecting the cursor."""
|
159 | 160 | if vendor == "postgresql":
|
160 |
| - # pylint: disable=import-outside-toplevel |
161 |
| - from psycopg2.extensions import parse_dsn |
162 |
| - |
163 |
| - if hasattr(cursor, "connection") and hasattr(cursor.connection, "dsn"): |
164 |
| - dsn = getattr(cursor.connection, "dsn", None) |
165 |
| - if dsn: |
166 |
| - data = parse_dsn(dsn) |
167 |
| - attrs[SpanAttributes.DB_NAME] = data.get("dbname") |
168 |
| - attrs[SpanAttributes.NET_PEER_NAME] = data.get("host") |
169 |
| - attrs[SpanAttributes.NET_PEER_PORT] = int(data.get("port")) |
| 161 | + info = getattr(getattr(cursor, "connection", None), "info", None) |
| 162 | + if not info: |
| 163 | + return attrs |
| 164 | + |
| 165 | + attrs[SpanAttributes.DB_NAME] = info.dbname |
| 166 | + is_unix_socket = info.host and info.host.startswith("/") |
| 167 | + |
| 168 | + if is_unix_socket: |
| 169 | + attrs[SpanAttributes.NET_TRANSPORT] = NetTransportValues.UNIX.value |
| 170 | + if info.port: |
| 171 | + # postgresql enforces this pattern on all socket names |
| 172 | + attrs[SpanAttributes.NET_PEER_NAME] = os.path.join( |
| 173 | + info.host, f".s.PGSQL.{info.port}" |
| 174 | + ) |
| 175 | + else: |
| 176 | + attrs[ |
| 177 | + SpanAttributes.NET_TRANSPORT |
| 178 | + ] = NetTransportValues.IP_TCP.value |
| 179 | + attrs[SpanAttributes.NET_PEER_NAME] = info.host |
| 180 | + if info.port: |
| 181 | + attrs[SpanAttributes.NET_PEER_PORT] = int(info.port) |
170 | 182 | return attrs
|
0 commit comments