Configuring Python's logging Module with argparse
This post assumes you're familiar with and using Python's logging module to log info from your script. If you don't care about how it works skip to the end to see the code for the full solution.
Goal
Our goal is to control the log level via the command line using an additional argument --log_level
that takes a one of the logging module's log levels.
$> script.py --log_level DEBUG
And it would be nice if the parsed variable returned by argparse.ArgumentParser.parse_args()
could be used directly as an argument to logging.Logger.setLevel
.
parsed_args = parser.parse_args()
root_logger = logging.getLogger()
root_logger.setLevel(parsed_args.log_level)