0

I write a simple script and user argparse for it. I can read the value args.verbose if the user supplied --verbose.

Now I want the change the logging config according to this flag.

If args.verbose is true, I want to see logger.debug, if it is false I don't want to see it (only logger.info and "more").

I don't do any logging up to now except at the top of the file:

import logging
logger=logging.getLogger(__name__)

Logging should go to stdout.

guettli
  • 25,042
  • 81
  • 346
  • 663

1 Answers1

2
import logging
import sys 
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose", help="increase output verbosity",
                    action="store_true")
args = parser.parse_args()

root = logging.getLogger()
root.setLevel(logging.INFO)
if args.verbose:
    root.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
root.addHandler(ch)

root.info(" Test Info")
root.debug("Test Debug")
Vinod Sharma
  • 883
  • 6
  • 13