Easier way to enable verbose logging

前端 未结 7 2269
一整个雨季
一整个雨季 2020-11-30 18:57

I want to add a debug print statement test, if I enable --verbose from the command line and if I have the following in the script.

logger.info(\         


        
相关标签:
7条回答
  • 2020-11-30 19:34

    Another variant would be to count the number of -v and use the count as an index to the a list with the actual levels from logging:

    import argparse
    import logging
    
    parser = argparse.ArgumentParser()
    parser.add_argument('-v', '--verbose', action='count', default=0)
    args = parser.parse_args()
    
    levels = [logging.WARNING, logging.INFO, logging.DEBUG]
    level = levels[min(len(levels)-1,args.verbose)]  # capped to number of levels
    
    logging.basicConfig(level=level,
                        format="%(asctime)s %(levelname)s %(message)s")
    
    logging.debug("a debug message")
    logging.info("a info message")
    logging.warning("a warning message")
    

    This works for -vvvv, -vvv, -vv, -v, -v -v , etc, If no -v then logging.WARNING is selected if more -v are provided it will step to INFO and DEBUG

    0 讨论(0)
提交回复
热议问题