Skip to content

Instantly share code, notes, and snippets.

@willprice
Created January 8, 2019 15:09
Show Gist options
  • Save willprice/352bb7cd40de33e73b84b93b9ab3d240 to your computer and use it in GitHub Desktop.
Save willprice/352bb7cd40de33e73b84b93b9ab3d240 to your computer and use it in GitHub Desktop.
Python argparse logging verbosity
import argparse
import logging
parser = argparse.ArgumentParser(
description="Demo of setting logging verbosity using -vvvv style args",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("-v", "--verbose", dest="verbosity", action="count", default=0,
help="Verbosity (between 1-4 occurrences with more leading to more "
"verbose logging). CRITICAL=0, ERROR=1, WARN=2, INFO=3, "
"DEBUG=4")
log_levels = {
0: logging.CRITICAL,
1: logging.ERROR,
2: logging.WARN,
3: logging.INFO,
4: logging.DEBUG,
}
if __name__ == '__main__':
args = parser.parse_args()
logging.basicConfig(level=log_levels[args.verbosity])
@alryaz
Copy link

alryaz commented Dec 1, 2021

@MaxenceG2M can be solved easily by doing something like:
logging.basicConfig(level=log_levels[min(args.verbosity, max(log_levels.keys()))])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment