Under Ubuntu I experiencetd that the usage of different debug levels for loggers to stdout and to file is not possible. In my Windows environment (Spyder with Anacosna) it works as expected. Please see my example code. Anyone has an idea what’s wrong here?
This is my example code:
import logging
#from logging.handlers import RotatingFileHandler
logfile = "log.log"
levels =('NOTSET', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')
dateformat = '%y-%m-%d %H:%M:%S'
strformat = '%(asctime)s %(levelname)s in %(funcName)s at %(lineno)s: %(message)s'
formatter = logging.Formatter(strformat,datefmt=dateformat)
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
logging.basicConfig(
format = strformat,
datefmt = dateformat,
force = True,
level = logging.WARNING,
)
if logfile:
print(f"Creating {logfile}")
fh = logging.FileHandler(logfile)
#fh = RotatingFileHandler(logfile, maxBytes=(1000), backupCount=1)
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
logging.getLogger('').addHandler(fh)
logging.debug(f"logging level is set to {levels[logging.root.level//10]}")
logging.warning("level warning test")
I would expect to see the debug level message in the file but this is not the case.
I see the warning in both, stdout and the file.
What am I doing wrong?
Do you need the logging module versions? How can I display the version?
2
Answers
I changed the code according to @Vinay's answer. Now I find the expected behavior
You need to look at the flow of information in logging, documented here. Since the root logger’s level is set to
WARNING
, it will not processDEBUG
orINFO
events, no matter what the levels are for any of the handlers attached to it.