Skip to content

Instantly share code, notes, and snippets.

@atomgomba
Last active September 13, 2019 14:12
Show Gist options
  • Save atomgomba/5df3aa6e668a68156efbc1592fcc395d to your computer and use it in GitHub Desktop.
Save atomgomba/5df3aa6e668a68156efbc1592fcc395d to your computer and use it in GitHub Desktop.
Python logging argparse utility for controlling logging level
from . import logging
from .logging import log
def main(args):
# set up logging from the arguments
logging.init(args)
log.info("hello world!")
if __name__ == "__main__":
parser = ArgumentParser()
# define your arguments here and then
# add the `-v` option to the argument parser
logging.add_argument(parser)
main(parser.parse_args())
import logging
from argparse import ArgumentParser, Namespace
log = logging
def init(args: Namespace):
logging.basicConfig(format='%(asctime)s %(module)s %(levelname)s: %(message)s')
levels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
if args.verbosity >= len(levels):
raise IndexError("Verbosity must be 0 <= n < 4")
logging.getLogger().setLevel(levels[args.verbosity])
def add_argument(parser: ArgumentParser):
parser.add_argument("-v", dest="verbosity", action="count", default=0,
help="Control verbosity")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment