Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
like image 230
Tesla001 Avatar asked Jul 24 '19 23:07

Tesla001


4 Answers

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__)
like image 189
BarryPye Avatar answered Oct 21 '22 09:10

BarryPye


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.' )
like image 20
Glazed Avatar answered Oct 21 '22 08:10

Glazed


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.

like image 45
ndclt Avatar answered Oct 21 '22 10:10

ndclt


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.

like image 32
blues Avatar answered Oct 21 '22 09:10

blues