code sample:
logger.add("file.log", format=fmt, enqueue=True, level="WARNING")
logger.warning("xxxxx")
do_others()
here now I want to set level to DEBUG
logger.debug("11111")
logger.info("aaaaa")
debug,info message can output.
Hello @zhouxiaomao.
It is not possible to modify the level of an handler once it has been added. There is several solutions, though.
You can remove an handler and restart it with updated level:
i = logger.add("file.log", format=fmt, enqueue=True, level="WARNING")
...
logger.remove(i)
logger.add("file.log", format=fmt, enqueue=True, level="DEBUG")
Alternatively, you can use a dynamic filter combined with .bind():
def my_filter(record):
if "warn_only" in record["extra"]:
return record["level"].no >= logger.level("WARNING").no
return True
logger.add("file.log", format=fmt, enqueue=True, level="DEBUG", filter=my_filter)
# Use this logger first, debug messages are filtered out
warn_logger = logger.bind(warn_only=True)
# Then you can use this one to log all messages
logger.debug("Blabla")
Or by using just one logger with a more advanced filter:
class MyFilter:
def __init__(self, level):
self.level = level
def __call__(self, record):
levelno = logger.level(self.level).no
return record["level"].no >= levelno
my_filter = MyFilter("WARNING")
logger.add(sys.stderr, "file.log", format=fmt, enqueue=True, filter=my_filter, level=0)
logger.warning("OK")
logger.debug("Nope")
my_filter.level = "DEBUG"
logger.debug("OK")
Thank you for your detailed explaination. I get it and try.
Most helpful comment
Hello @zhouxiaomao.
It is not possible to modify the level of an handler once it has been added. There is several solutions, though.
You can remove an handler and restart it with updated level:
Alternatively, you can use a dynamic
filtercombined with.bind():Or by using just one logger with a more advanced filter: