I have recently started using Python Loguru so in order to better understand the library I have created a couple of tests, here's one:
from loguru import logger
import random
loggerEven = logger
loggerEven.add("Even.txt", mode='w', level="INFO")
loggerUneven = logger
loggerUneven.add("UnEven.txt", mode='w', level="ERROR")
x = random.randint(0, 11)
print(x)
if x%2 == 1:
loggerUneven.error("Uneven")
else:
loggerEven.info("Even")
So, if the number is even - all is well. However, when I get an uneven number, the log is written both to Even.txt and UnEven.txt files. I tried changing loggerUneven.error to loggerUneven.info and to loggerUneven.success, though in the latter cases the logs are written to Even.txt, is there any way to make files Uneven/error files to be written only to the corresponding file not to every log files?
I have recently started using Python Loguru so in order to better understand the library I have created a couple of tests, here's one:
from loguru import logger
import random
loggerEven = logger
loggerEven.add("Even.txt", mode='w', level="INFO")
loggerUneven = logger
loggerUneven.add("UnEven.txt", mode='w', level="ERROR")
x = random.randint(0, 11)
print(x)
if x%2 == 1:
loggerUneven.error("Uneven")
else:
loggerEven.info("Even")
So, if the number is even - all is well. However, when I get an uneven number, the log is written both to Even.txt and UnEven.txt files. I tried changing loggerUneven.error to loggerUneven.info and to loggerUneven.success, though in the latter cases the logs are written to Even.txt, is there any way to make files Uneven/error files to be written only to the corresponding file not to every log files?
loguruloggers don't work quite how you think. YourloggerEvenandloggerUnevenare both actually the same logger object. So you've added two file sinks to the same logger! This is why you're seeing duplicates.You can verify this with:
This will print
True, demonstrating that they are both the same logger.However, although you've added two sinks to the same logger, you've added them with different
levelarguments. This is why your.error(..)call goes to both files, but your.info(..)call goes to both.You should look at the
filterargument to.add(..).The
logurudocs are excellent and have an example of exactly what you're trying to achieve:https://loguru.readthedocs.io/en/stable/resources/recipes.html#creating-independent-loggers-with-separate-set-of-handlers