Skip to content

LoggingConnection keeps connections open even after the Garbage Collector is run #1670

Open
@spatankar-dmpna

Description

@spatankar-dmpna

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)

`

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions