[Python] how to set logging level from command line

Discussão em 'Python' iniciado por Stack, Dezembro 22, 2024.

  1. Stack

    Stack Membro Participativo

    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')

    Continue reading...

Compartilhe esta Página