loguru
loguru copied to clipboard
separate log files for modules
I have two classes in two python files that need two separate log files. The two classes would look like this :
from loguru import logger
class Test1:
def __init__(self):
self.logger = logger.bind(name="Test1")
self.logger.remove()
self.logger.add("loguru_tests/test1.log", filter=lambda record: record["extra"].get("name") == "Test1")
self.logger.debug("Test1 class created")
def test1(self):
self.logger.debug("Test1 class test1 method")
and
from loguru import logger
class Test2:
def __init__(self):
self.logger = logger.bind(name="Test2")
self.logger.remove()
self.logger.add("loguru_tests/test2.log", filter=lambda record: record["extra"].get("name") == "Test2")
self.logger.debug("Test class created")
def test2(self):
self.logger.debug("Test2 class test2 method")
And then my main like that :
from class1 import Test1
from class2 import Test2
if __name__ == "__main__":
t2 = Test2()
t1 = Test1()
t2.test2()
t1.test1()
But i can't manage two have the logs from the test2() method, which parent class is instantiated first. I read the docs and didn't find the answer to this problem. Thanks for help !
Hi @Serlonwann.
It seems you simply need to delete the self.logger.remove() lines in the __init__() method of your classes. Calling logger.remove() will erase all previously installed handlers. That will lead to unexpected results depending on which order you instantiate Test1 and Test2 classes. Instead, yo can call logger.remove() at the beginning of your if __name__ == "__main__" branch.