Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

separate log files for modules #1157

Open
Serlonwann opened this issue Jun 19, 2024 · 1 comment
Open

separate log files for modules #1157

Serlonwann opened this issue Jun 19, 2024 · 1 comment

Comments

@Serlonwann
Copy link

Serlonwann commented Jun 19, 2024

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 !

@Delgan
Copy link
Owner

Delgan commented Jun 23, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants