Skip to content

Commit

Permalink
fix wrong logging behavior
Browse files Browse the repository at this point in the history
1. Handler configuration based on the result of "get_config" in main function,
but if something wrong happens in "get_config", the "logger.handlers" will
be empty, and result in the error 'No handlers could be found for logger "altsrc"'.

Add logging.basicConfig in main function for root logger's default handler creation,
this is used to catch log before "setup_logging" is called.

Update logic in setup_logging: only the root logger has handlers.

2. Add an autouse pytest fixture "reset_loggers" in conftest.py. It saves the
handlers before each test, then puts them back after end of the test. It keeps the
loggers and handlers in every test consistent.
  • Loading branch information
dichn committed Nov 25, 2020
1 parent 810c98a commit 4486ce4
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
7 changes: 5 additions & 2 deletions alt_src/alt_src.py
Original file line number Diff line number Diff line change
Expand Up @@ -2120,8 +2120,7 @@ def die(msg):


def setup_logging(options):
logger = logging.getLogger("altsrc")
logger.setLevel(logging.DEBUG)
logger = logging.getLogger()

#determine log levels
output_log_level = logging.WARN #default
Expand All @@ -2141,6 +2140,9 @@ def setup_logging(options):
file_log_level = min(file_log_level, output_log_level)
options.file_log_level = file_log_level

# remove the default handler of root logger
logger.handlers = []

# set up handlers
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter(options.config['log_format']))
Expand Down Expand Up @@ -2199,6 +2201,7 @@ def main(args):
options.branch = args[0]
options.source = args[1]

logging.basicConfig(level=logging.DEBUG)
options.config = get_config(options.cfile, options.copts)

logger = setup_logging(options)
Expand Down
12 changes: 12 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import logging

import pytest


@pytest.fixture(autouse=True)
def reset_loggers():
root_handlers = logging.getLogger().handlers[:]
altsrc_handlers = logging.getLogger("altsrc").handlers[:]
yield
logging.getLogger().handlers = root_handlers
logging.getLogger("altsrc").handlers = altsrc_handlers

0 comments on commit 4486ce4

Please sign in to comment.