Last active
September 13, 2019 14:12
-
-
Save atomgomba/5df3aa6e668a68156efbc1592fcc395d to your computer and use it in GitHub Desktop.
Python logging argparse utility for controlling logging level
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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