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?
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.
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.
By default, Django uses the dictConfig format. In order to configure logging, you use LOGGING to define a dictionary of logging settings.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With