Skip to content

Performance regression: Logger()/LogReader() factories re-scan all entry_points on every construction since 4.4.0 (plugin cache guard was dropped) #2155

Backlog

Description

@aydin-can-2026

Summary

Since python-can 4.4.0, can.Logger() and can.LogReader() call _update_writer_plugins() / _update_reader_plugins() unconditionally on every construction, which performs a full importlib.metadata.entry_points(group="can.io.message_writer") scan of the whole virtualenv. In 4.0.0–4.3.1 this scan was guarded by a class-level fetched_plugins flag and ran once per process. The guard was silently dropped during the 4.4.0 refactor of Logger from a class into a factory function.

In a typical venv (230+ distributions, ~2000 entry point entries) this makes each Logger() call take ~11 ms on Python 3.10 (where entry_points(group=...) is not cached), instead of ~0.1 ms.

This is not just a microbenchmark issue — see Real-world impact below.

Version history (verified against wheels/sdists of 3.3.2, 4.0.0, 4.2.0, 4.2.2, 4.3.0, 4.3.1, 4.4.0, 4.5.0, 4.6.0, 4.6.1)

Version Mechanism Scan frequency
3.3.2 Logger class, hardcoded filename.endswith(...) branches never
4.0.0 entry_points via pkg_resources, guarded by Logger.fetched_plugins once per process
4.2.x same, fetched_plugins kept once per process
4.3.0/4.3.1 pkg_resources replaced by internal read_entry_points() (importlib.metadata), fetched_plugins kept once per process
4.4.0 Logger refactored from class to plain factory function; module-level MESSAGE_WRITERS dict + _update_writer_plugins(); guard removed, called unconditionally in the function body every construction
4.5.0 – 4.6.1 unchanged every construction

Current code (4.6.1, can/io/logger.py):

def Logger(filename, **kwargs):
    if filename is None:
        return Printer(**kwargs)

    _update_writer_plugins()   # <-- unconditional, full entry_points scan every call

    suffix = pathlib.PurePath(filename).suffix.lower()
    ...

The 4.3.1 code it replaced:

class Logger(MessageWriter):
    fetched_plugins = False

    @staticmethod
    def __new__(cls, filename, *args, **kwargs):
        ...
        if not Logger.fetched_plugins:
            Logger.message_writers.update(
                {writer.key: writer.load()
                 for writer in read_entry_points("can.io.message_writer")}
            )
            Logger.fetched_plugins = True   # <-- ran once per process
        ...

The changelog for 4.4.0 does not mention any intended change to plugin loading behavior, so the guard removal looks like an unintentional regression of the refactor, not a deliberate trade-off.

Reproduction

import time
import can
import can.io.logger as cl

N = 20

t0 = time.perf_counter()
for _ in range(N):
    can.Logger("/tmp/bench.log")
print(f"{(time.perf_counter() - t0) / N * 1000:.2f} ms per Logger()  (current code)")

# emulate the 4.3.x behaviour: scan once, then cache
cl._update_writer_plugins()
cl._update_writer_plugins = lambda: None

t0 = time.perf_counter()
for _ in range(N):
    can.Logger("/tmp/bench.log")
print(f"{(time.perf_counter() - t0) / N * 1000:.2f} ms per Logger()  (cached)")

Typical output in a project venv on Python 3.10 (venv with ~230 installed distributions):

11.32 ms per Logger()  (current code)
0.12 ms per Logger()  (cached)

Same applies to LogReader() via _update_reader_plugins() (can/io/player.py).

Real-world impact

We hit this in a CAN bus regression-testing framework that records 9 CAN-FD buses concurrently (one recording task per bus, each constructing can.Logger() + can.Notifier() in a thread pool). With 4.6.1:

  • the 9 concurrent Logger() constructions are serialized by the GIL and stretch from ~100 ms total to ~2.0–2.3 s;
  • during that window the kernel receive buffer of each already-created SocketCAN socket (212 KB ≈ 222 CAN-FD frames at ~959 B/skb) fills up and the kernel drops frames — the resulting logs show a 1.3–2 s hole right at the start of each recording;
  • with python-can 3.3.2 on the same bench, the same test passes deterministically, because Logger() construction takes ~0.1 ms and consumption starts before the buffer can fill.

CPU profiling confirmed 96 ms out of 100 ms (9 constructions) is spent inside importlib.metadata entry_points scanning, not in actual work.

Suggested fix

Restore the process-level cache that existed in 4.0–4.3, e.g. with functools.lru_cache (applies to both can/io/logger.py and can/io/player.py):

from functools import lru_cache

@lru_cache(maxsize=None)
def _update_writer_plugins() -> None:
    """Update available message writer plugins from entry points (once per process)."""
    for entry_point in read_entry_points("can.io.message_writer"):
        if entry_point.key in MESSAGE_WRITERS:
            continue
        writer_class = entry_point.load()
        if issubclass(writer_class, MessageWriter):
            MESSAGE_WRITERS[entry_point.key] = writer_class

This keeps third-party plugin support intact (plugins are discovered on the first Logger()/LogReader() call of the process), while eliminating the repeated full scan.

Happy to open a PR if you agree with the approach.

Environment

  • python-can: 4.4.0 – 4.6.1 (verified per-version from wheels)
  • Python: 3.10.x
  • OS: Linux (Ubuntu 22.04), also reproducible on any venv with many installed packages

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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