4

I would like to use a different logging level in development and production. To do so, I need early in my program to set the minimal level for logs to be triggered. The default is to output all severities:

from loguru import logger as log

log.debug("a debug log")
log.error("an error log")

# output
# 2022-09-15 16:51:23.325 | DEBUG    | __main__:<module>:3 - a debug log
# 2022-09-15 16:51:23.327 | ERROR    | __main__:<module>:4 - an error log

There is a Changing the level of an existing handler section in the documentation, that states among others that

Once a handler has been added, it is actually not possible to update it. (...)

The most straightforward workaround is to remove() your handler and then re-add() it with the updated level parameter.

My problem is that I have not added anything, so there is nothing to remove. I also cannot modify log. So what should I do?

WoJ
  • 27,165
  • 48
  • 180
  • 345

1 Answers1

10

Like so:

import sys
from loguru import logger as log
log.remove() #remove the old handler. Else, the old one will work along with the new one you've added below'
log.add(sys.stdout, level="INFO") 
log.debug("debug message")
log.info("info message")
log.warning("warning message")
log.error("error message") 

You can use sys.stdout or other file object, in place of sys.stdout.
More info in this related GitHub thread.

Nav
  • 19,885
  • 27
  • 92
  • 135
kwiknik
  • 570
  • 3
  • 7