Conditional log level on a statement in python?
logging, python
Solution
Use `Logger.log()` instead of the functions named after levels; this takes a level as the first argument:
entire_set = len(data) == len(train) + len(test)
logging.log(logging.WARNING if entire_set else logging.INFO,
"Entire data set allocated => {0}".format(entire_set))
The `logging.warning()` and `logging.info()` functions are merely shortcuts for calling `logging.log()` with a given log level.
You probably want to switch to using a dedicated `Logger` object rather than use the module-level functions; it'll allow you to configure logging more granularly and track where log messages came from by their logger name.
Problem
Is there a way to dynamically set which log level I want a statement logged as? I have this code: ``` logging.info("Data Set Size => {0}".format(len(data))) logging.info("Training Set Size => {0}".format(len(train))) logging.info("Test Set Size => {0}".format(len(test))) logging.info("Entire data set allocated => {0}".format(len(data) == len(train) + len(test))) ``` It very nicely outputs something similar to this, depending on the format I've set: ``` root : INFO Data Set Size => 10000 root : INFO Training Set Size => 7500 root : INFO Test Set Size => 2500 root : INFO Entire data set allocated => True ``` Now, the question I have, if the logic check in that last line is `False`, can I set that level to a `.warning`? I could do something like this: ``` if len(data) == len(train) + len(test): logging.info("Entire data set allocated => {0}".format(True) else: logging.warning("Entire data set allocated => {0}".format(False) ``` But, is there a way to do it in fewer lines?