To start with we’ll need a list of all the possible log levels. Unfortunately there isn’t a nice way of gathering all the log levels programmatically. We could try and capture all constants (everything in the logging module with all capital letters) but that would capture some extra constants that we don’t want (logging.BASIC_FORMAT, logging.WARN, etc.). So instead of that let’s start by manually listing the log levels.
Next we’ll need a function to convert from the log level string to an int that can be passed to logging.Logger.setLevel. This function will be the type= keyword argument when calling argparse.ArgumentParser.add_argument.
Let’s check that the value received from the command line is one of the allowed values and then if it is we can retrieve its int value from the logging namespace using getattr. The extra assert checks that the logging library hasn’t removed or altered the meanings of one of our expected log levels.
Now all that’s left to do is add our new argument to our ArgumentParser.