click-log icon indicating copy to clipboard operation
click-log copied to clipboard

Add `@verbosity_option` decorator

Open phijor opened this issue 4 years ago • 1 comments

Hi, I use click_log for an application with many logger instances, each of which outputs a lot of debug information. To make debugging a single component easier, I implemented a custom decorator @verbosity_option that makes it possible to silence parts of the application.

Is this a feature that would be useful to have in click_log? Naming is up for debate and documentation can surely be improved. Also I'm not quite sure what the minimum python version is that should be supported (I used f-strings and maybe some other "new" features in there).

Below is the commit message for this pull request:

This decorator is intended for complex applications which have multiple nested logger instances. It can be used to selectivly toggle log levels for loggers and their child loggers. A use case for this would be when one has a large application that has a detailed debug output across its modules. When debugging a single module, one wants to silence debug output of all modules except for this one.

Imagine an application with multiple logger instance such as this:

from logging import getLogger
from click import command
from click_log import verbosity_option, basic_config

app_logger = getLogger(__name__)

# imagine these are loggers in submodules, using python's
# hierarchical logger naming scheme
foo_logger = getLogger(__name__ + ".foo")
bar_logger = getLogger(__name__ + ".bar")

basic_config(app_logger)

@command()
@verbosity_option(app_logger)
def main():
    app_logger.info("Hello world from App")
    foo_logger.debug("Do foo-stuff")
    bar_logger.debug("Frobnicating doobles in bar")

if __name__ == "__main__":
    main()

The verbosity options provided by this decorator take a comma-separated list of <LOGGER>=<LEVEL> assignments (which set levels for child loggers of the app_logger) or <LEVEL> statements (which set the verbosity of app_logger itself). Running

$ ./script.py -v INFO,foo=DEBUG

then prints

Hello world from App
debug: Do foo-stuff

Notice how the output of bar_logger was supressed, as python loggers inherit their log level from their parent loggers; in this case app_logger.

This decorator is a drop-in replacement for @simple_verbosity_option; supplying -v <LEVEL> does exactly the same for both decorators.

phijor avatar Sep 25 '19 19:09 phijor

CI told me to be compatible with python 2.7. That's fair, I guess.

phijor avatar Sep 25 '19 20:09 phijor