I've written a python cli with the 'click' library. I'd like to also use python's built-in logging
module for logging to the console. But I've struggled getting the logging messages to the console. I tried a very simple approach:
logger = logging.getLogger(__name__)
@click.command()
def cli():
logger.setLevel("INFO")
logger.info("Does this work?")
print("done.")
The logger content doesn't appear in my console. Maybe it needs a handler to explicitly send log messages to stdout?
logger = logging.getLogger(__name__)
@click.command()
def cli():
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter('%(asctime)s %(message)s'))
handler.setLevel("INFO")
logger.addHandler(handler)
logger.info("Does this work?")
print("done.")
Unfortunately this also doesn't work.
A third option--creating a handler and setting loglevels for the handler and the logger-- works:
logger = logging.getLogger(__name__)
@click.command()
def cli():
logger.setLevel("INFO")
handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(logging.Formatter('%(asctime)s %(message)s'))
handler.setLevel("INFO")
logger.addHandler(handler)
logger.info("Does this work?")
print("done.")
It seems like:
- if creating a logger with
logging.getLogger
, I have to create a handler for my logger explicitly. - and I have to set a loglevel on both the logger and the handler?
Is that right? It seems silly to set the level twice. What's the point?
Or am I still misunderstanding the right way to do this?
Thanks for your help!
logging.basicConfig(level=logging.INFO, format='%(message)s')
to get output without"INFO:root:"
– Crusado