Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : How to set logging level for all loggers to INFO

Tags:

python

logging

I am using following config

import logging


FORMAT = '%(levelname)s: %(asctime)-15s: %(filename)s: %(funcName)s: %(module)s: %(message)s'
logging.basicConfig(filename="/var/log/out.log", level=logging.INFO, format=FORMAT)
LOGGER = logging.getLogger("Customer")

And then there some libraries which I have imported. Those Libraries have debug logging statements like

 LOGGER = logging.getLogger(__name__)
 LOGGER.debug('add_timeout: added timeout %s; deadline=%s at %s',
                     timeout_id, deadline, timeout_at)

When I run my program it prints debug logs of internal libraries as well. I want to avoid debug logs at all.

like image 851
hard coder Avatar asked Jan 04 '19 09:01

hard coder


People also ask

How do I create a multiple logging level in Python?

You can set a different logging level for each logging handler but it seems you will have to set the logger's level to the "lowest". In the example below I set the logger to DEBUG, the stream handler to INFO and the TimedRotatingFileHandler to DEBUG. So the file has DEBUG entries and the stream outputs only INFO.

How do you change the log level in Python?

The logging level is set with setLevel . It sets the threshold for this logger to lvl . Logging messages which are less severe than lvl will be ignored. In the example, we change the logging level to DEBUG .

How do you pass variables to logging information in Python?

We can add variable data into our logs using any formatting style, like the f-strings introduced in Python 3.6. 00:16 In this example, I've defined a variable called name and it's holding the string 'John' . Then I log a new event with the level ERROR and I give it the message of f'{name} raised an error' .


1 Answers

The below code should do the trick.

loggers = [logging.getLogger(name) for name in logging.root.manager.loggerDict]
for logger in loggers:
    logger.setLevel(logging.INFO)

The first line returns the list of logs instantiated. The for loop just sets the level to all the logs.

P.S. credits to https://stackoverflow.com/a/53250066/4696783

like image 65
alcaprar Avatar answered Oct 22 '22 01:10

alcaprar