Skip to content

fix: make setup_logger idempotent - #14

Draft
MattL1989 wants to merge 1 commit into
masterfrom
fix/setup-logger-idempotent
Draft

MattL1989 wants to merge 1 commit into
masterfrom
fix/setup-logger-idempotent

Conversation

@MattL1989

Copy link
Copy Markdown
Owner

Problem

appium.common.logger.setup_logger() creates and attaches a new stderr StreamHandler on every call. The module already calls it once on import. So when a user calls the public setup_logger() again, for example to change the log level, every message is printed twice:

import logging
from appium.common.logger import logger, setup_logger

setup_logger(logging.DEBUG)
logger.debug('hello')
# hello
# hello
len(logger.handlers)  # 2

Each further call adds one more copy.

Fix

  • Create the stderr handler once, at module level, and attach that same handler in setup_logger().
  • Logger.addHandler skips a handler that is already attached, so repeated calls don't add handlers. If the handler was removed, the next call attaches it again.
  • The level passed in is still applied on every call.
  • propagate = False is unchanged.

Tests

  • New test/unit/common/logger_test.py:
    • test_setup_logger_does_not_add_another_handler: calling setup_logger() twice leaves the single stderr handler from import. Without the fix, there are two more handlers.
    • test_setup_logger_updates_level: calling it again with a different level still changes the level, and propagate stays False.
  • The tests count only plain StreamHandlers, because pytest attaches its own capture handlers to non-propagating loggers while a test runs.
  • ruff check, ruff format --check, mypy appium and the full unit test suite pass.

🤖 Generated with Claude Code

`setup_logger()` created and attached a new stderr `StreamHandler` on
every call. The module already calls it once on import, so a user calling
the public `setup_logger()` again, for example to change the log level,
got a second handler and every message was printed twice.

Create the stderr handler once at module level and attach that same
handler in `setup_logger()`. `Logger.addHandler` skips a handler that is
already attached, so repeated calls no longer add handlers, while the
level passed in is still applied on every call. `propagate = False` is
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant