Skip to content

Instantly share code, notes, and snippets.

@ms5
Last active July 19, 2024 12:19
Show Gist options
  • Save ms5/9f6df9c42a5f5435be0e to your computer and use it in GitHub Desktop.
Save ms5/9f6df9c42a5f5435be0e to your computer and use it in GitHub Desktop.
manipulating log level with python argparse
import argparse
import logging
parser = argparse.ArgumentParser()
parser.add_argument('--verbose', '-v', action='count', default=1)
args = parser.parse_args()
args.verbose = 70 - (10*args.verbose) if args.verbose > 0 else 0
logging.basicConfig(level=args.verbose, format='%(asctime)s %(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
logging.debug('im a DEBUG message')
logging.info('im a INFO message')
logging.warning('im a WARNING message')
logging.critical('im a CRITICAL message')
logging.error('im a ERROR message')
@ms5
Copy link
Author

ms5 commented Feb 4, 2015

purpose

example to show how to manipulate log levels with python argparse. basically add more 'v' to the start parameters will increase the log level to higher verbosity. This example defaults log nothing (be silent) without any parameters given.

examples:

  • default is to log nothing (be silent)
 $verbos-argpary-example.py
 $
  • will log CRITICAL level
 $verbos-argpary-example.py -v
 2015-02-04 11:00:46 CRITICAL: im a CRITICAL message
  • will log everything up to WARNING level
 $verbos-argpary-example.py -vvv 
 2015-02-04 10:59:22 WARNING: im a WARNING message
 2015-02-04 10:59:22 CRITICAL: im a CRITICAL message
 2015-02-04 10:59:22 ERROR: im a ERROR message
  • at some point adding more -v does not have an impact anymore
 $verbos-argpary-example.py -vvvvvvvvvv
 2015-02-04 11:09:18 DEBUG: im a DEBUG message
 2015-02-04 11:09:18 INFO: im a INFO message
 2015-02-04 11:09:18 WARNING: im a WARNING message
 2015-02-04 11:09:18 CRITICAL: im a CRITICAL message
 2015-02-04 11:09:18 ERROR: im a ERROR message

@myselfhimself
Copy link

Thanks for posting this!! I used a level of 40 instead, so that logging.info() messages trigger from the first -v
args.verbose = 40 - (10*args.verbose) if args.verbose > 0 else 0
Best :)

@avrahamshukron
Copy link

avrahamshukron commented Mar 25, 2020

This is so great. Thank you.

I also recommend setting the initial value to 40.

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