psycopg2 icon indicating copy to clipboard operation
psycopg2 copied to clipboard

LoggingConnection keeps connections open even after the Garbage Collector is run

Open spatankar-dmpna opened this issue 1 year ago • 0 comments

Please complete the following information:

  • OS: Windows
  • Psycopg version: 2.8.3
  • Python version: 3.6
  • PostgreSQL version: 13
  • pip version: conda 23.7.4

Describe the bug Please let us know:

1: what you did We have subclassed LoggingConnection and LoggingCursor for our project. In our initial design we were relying on the garbage collectors to close our connection at the end of the function scopes. This was bad design and has since been fixed. 2: what you expected to happen The garbage collector should have destroyed the LoggingConnection object at the end the function scope. 3: what happened instead The LoggingConnection object remained alive because it still had a reference to it.

Explanation:

Looking into the issue, it looks like the LoggingConnection still had a reference to it because of the bound method "log"

`

def initialize(self,  logobj):
    self._logobj = logobj
    if _logging and isinstance(logobj, (_logging.Logger, _logging.LoggerAdapter)):
         self.log = self._logtologger
    else:
        self.log = self._logtofile

`

The Solution:

The methods should be bound with a weak reference instead

`

def initialize(self, logobj):
    self._logobj = logobj
    if _logging and isinstance(logobj, (_logging.Logger, _logging.LoggerAdapter)):
        self._log = weakref.WeakMethod(self._logtologger)
   else:
        self._log = weakref.WeakMethod(self._logtofile)

def log(self, *args, **kwargs):
   return self._log()(*args, **kwargs)

`

spatankar-dmpna avatar Feb 05 '24 23:02 spatankar-dmpna