简体   繁体   中英

how to set logging level from command line

I'm using argparse to get the logging level from the command line and then passing it as input for logging.basicConfig. However, the way I'm trying to implement this is not working. Any suggestion?

Desire behavior, from command line:

python main.py -log=DEBUG

Desire output

DEBUG:__main__: Debug is working

Code

import logging
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-log", "--log", nargs='+', help="Provide logging level. Example --log debug'")

log_level = parser.parse_args().log
log_level = 'logging.'+log_level[0]
print(log_level)
logging.basicConfig(level=log_level)
logger = logging.getLogger(__name__) 
logger.debug(' Debug is working')

Putting these combinations together, allowing the user to name the level with upper or lower case, allowing only one level to be specified, and picking the explicit level from a dictionary with a default to the WARNING level:

import argparse
import logging
parser = argparse.ArgumentParser()
parser.add_argument(
    "-log", 
    "--log", 
    default="warning",
    help=(
        "Provide logging level. "
        "Example --log debug', default='warning'"),
    ),
)

options = parser.parse_args()
levels = {
    'critical': logging.CRITICAL,
    'error': logging.ERROR,
    'warn': logging.WARNING,
    'warning': logging.WARNING,
    'info': logging.INFO,
    'debug': logging.DEBUG
}
level = levels.get(options.log.lower())
if level is None:
    raise ValueError(
        f"log level given: {options.log}"
        f" -- must be one of: {' | '.join(levels.keys())}")
logging.basicConfig(level=level)
logger = logging.getLogger(__name__)

The level should be a variable from logging not a string, logging.DEBUG for example. I think you have to create a dict matching the given argument and the logging variable:

level_config = {'debug': logging.DEBUG, 'info': logging.INFO} # etc.
log_level = level_config[parser.parse_args().log[0].lower()]

You can also add choices=['debug', 'info', 'warning'] in your add_argument call.

The basicConfig function can take a string argument for level , and it will check its validity for you, so the code can be much simpler than BarryPye's answer.

import argparse
import logging

parser = argparse.ArgumentParser()
parser.add_argument( '-log',
                     '--loglevel',
                     default='warning',
                     help='Provide logging level. Example --loglevel debug, default=warning' )

args = parser.parse_args()

logging.basicConfig( level=args.loglevel.upper() )
logging.info( 'Logging now setup.' )

log_level = 'logging.'+log_level[0] this just makes the string 'logging.DEBUG' which is not something that basicConfig understands. what it want's is the logging.DEBUG constant which you can get by getattr(logging, log_level[0]) . Newer versions of python actually accept the textual representation as well and you can just pass in 'DEBUG' as level.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM