Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set global minimum logging level across all loggers in Python/Django

At the time of invocation of my application, I'd like to be able to read in (from config or command line or environment variable) the minimum logging level across ALL of my loggers and then globally set the logging module to respect this MIN_LOGGING_LEVEL.

For example, something like this (which doesn't exist): logging.setLevel(logging.INFO)

I understand that I can individually, on the loggers and on handlers, set the logging levels, as well as create filters for handlers to respect things like the DEBUG flag. However, what I really want is to be able to change the minimum log level across all loggers at invocation time (and depending on environment, for example).

Do I have to roll this myself and construct the configuration dynamically at runtime to accomplish this? Or is there a better way or pattern that I'm not seeing?

like image 663
ValAyal Avatar asked Jul 24 '14 16:07

ValAyal


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 many levels are defined in logging module?

There are six log levels in Python; each level is associated with an integer that indicates the log severity: NOTSET=0, DEBUG=10, INFO=20, WARN=30, ERROR=40, and CRITICAL=50.

What is the type of configuration Django requires for logging?

By default, Django uses the dictConfig format. In order to configure logging, you use LOGGING to define a dictionary of logging settings.


2 Answers

You can use logging.disable - the following ensures logging.INFO and below are disabled:

logging.disable(logging.INFO)

From the documentation:

Its effect is to disable all logging calls of severity lvl and below, so that if you call it with a value of INFO, then all INFO and DEBUG events would be discarded, whereas those of severity WARNING and above would be processed according to the logger’s effective level.

To undo it later, you can call:

logging.disable(logging.NOTSET)
like image 84
Simeon Visser Avatar answered Sep 19 '22 13:09

Simeon Visser


As an alternative to using the disable function, you can override the default level setting of WARNING as follows:

import logging
logging.getLogger().setLevel(logging.INFO)  # choose your level here

I wouldn't call this a global solution per-se, as it requires a file-level declaration, but it's useful IMO for simple debugging during development before a more cohesive project hierarchy has been established.

like image 37
alphazwest Avatar answered Sep 23 '22 13:09

alphazwest