> cat verbose.py
#!/usr/bin/env python
import argparse
import logging
parser = argparse.ArgumentParser(
description='A test script for http://stackoverflow.com/q/14097061/78845'
)
parser.add_argument("-v", "--verbose", help="increase output verbosity",
action="store_true")
args = parser.parse_args()
if args.verbose:
logging.basicConfig(level=logging.DEBUG)
logging.debug('Only shown in debug mode')
Run the help:
> ./verbose.py -h
usage: verbose.py [-h] [-v]
A test script for http://stackoverflow.com/q/14097061/78845
optional arguments:
-h, --help show this help message and exit
-v, --verbose increase output verbosity
Running in verbose mode:
> ./verbose.py -v
DEBUG:root:Only shown in debug mode
So if --debug is set, the logging level is set to DEBUG. If --verbose, logging is set to INFO. If neither, the lack of --debug sets the logging level to the default of WARNING.
2017-07-18: I've since switched to a different method:
logging.basicConfig(level=logging.DEBUG if __debug__ else logging.INFO)
what this does is, if you're running without optimization (as in python script.py) you get the DEBUG-level stuff, whereas if you run with python -OO script.py you don't. no environment variables to set.
Here's another take on having argparse count the -v option to increase verbosity up two levels from the default WARNING to INFO (-v) to DEBUG (-vv). This does not map to the constants defined by logging but rather calculates the value directly, limiting the input:
print( "Verbosity / loglevel:", args.v )
logging.basicConfig( level=10*(3-max(0,min(args.v,3))) )
logging.debug("debug") # 10
logging.info("info") # 20
logging.warning("warning") # 30 - The default level is WARNING, which means that only events of this level and above will be tracked
logging.error("error") # 40
logging.critical("critical") # 50