|
| 1 | +from newrelic import agent |
| 2 | +from newrelic.hooks.database_dbapi2 import ( |
| 3 | + ConnectionFactory as DBAPI2ConnectionFactory, |
| 4 | +) |
| 5 | + |
| 6 | + |
| 7 | +class ConnectionFactory(DBAPI2ConnectionFactory): |
| 8 | + """""" |
| 9 | + |
| 10 | + @staticmethod |
| 11 | + async def __connection_wrapper__(wrapped, *args, **kwargs): |
| 12 | + return await wrapped |
| 13 | + |
| 14 | + def __call__(self, *args, **kwargs): |
| 15 | + agent.wrap_function_wrapper(kwargs['connection_class'], '_execute', self._execute_wrapper) |
| 16 | + return super(ConnectionFactory, self).__call__(*args, **kwargs) |
| 17 | + |
| 18 | + |
| 19 | + async def _execute_wrapper(self, wrapped, instance, args, kwargs): |
| 20 | + |
| 21 | + db_host, db_port = instance._addr |
| 22 | + db_name = instance._params.database |
| 23 | + |
| 24 | + trace_kwargs = { |
| 25 | + "transaction": agent.current_transaction(), |
| 26 | + "dbapi2_module": self._nr_dbapi2_module, |
| 27 | + "connect_params": ((db_host, db_port, db_name), {}), |
| 28 | + "sql": args[0], |
| 29 | + "sql_parameters": args[1:] |
| 30 | + } |
| 31 | + |
| 32 | + with agent.DatabaseTrace(**trace_kwargs): |
| 33 | + return await wrapped(*args, **kwargs) |
| 34 | + |
| 35 | + |
| 36 | +def instrument(module): |
| 37 | + |
| 38 | + agent.register_database_client( |
| 39 | + module, |
| 40 | + database_product='Postgres', |
| 41 | + quoting_style='single+dollar', |
| 42 | + explain_query='explain', |
| 43 | + explain_stmts=('select', 'insert', 'update', 'delete'), |
| 44 | + ) |
| 45 | + |
| 46 | + agent.wrap_object(module, 'connection.connect', ConnectionFactory, (module,)) |
| 47 | + agent.wrap_object(module, 'connect', ConnectionFactory, (module,)) |
0 commit comments