2

I have two logging classes, that should print logs on two different files.

First class

import logging

class firstLog:
    
    def __init__(self):
        self.logger = logging.getLogger("my_logger1")
        logging.basicConfig(format="%(asctime)s.%(msecs)06d:\n%(message)s\n", level=logging.DEBUG,
                            datefmt="%d/%m/%Y %H:%M:%S",
                            filename="filename1.log")

    def printlog(self, msg, *args, **kwargs):
        self.logger.debug(msg, *args, **kwargs)

Second class

import logging

class secondLog:
    
    def __init__(self):
        self.logger = logging.getLogger("my_logger2")
        logging.basicConfig(format="%(asctime)s.%(msecs)06d:\n%(message)s\n", level=logging.DEBUG,
                            datefmt="%d/%m/%Y %H:%M:%S",
                            filename="filename2.log")

    def printlog(self, msg, *args, **kwargs):
        self.logger.debug(msg, *args, **kwargs)

I instantiate the two classes, but only filename1.log is written

log1 = firstLog()
log2 = secondLog()

log1.printlog("text1")
log2.printlog("text2")

What I obtain is that a new file, called filename1.log is created, and contains

04/06/2021 08:57:04.000988:
text1
04/06/2021 08:57:04.000990:
text2

but I need two separate files

2 Answers 2

4

logging.basicConfig() is only applied once.

If logging has been configured already, basicConfig() will do nothing unless force is set. (source)

In your case you should get separate loggers with logging.getLogger(name) and different names. Then configure the loggers manually.

Sign up to request clarification or add additional context in comments.

1 Comment

You should have a look at the How-to. It explains a lot about the concepts of the logging package and how to configure it. You will also see way many developers use getLogger(__name__) instead of creating loggers manually.
1

logging.basicConfig() is meant to be run once at your app's startup time, and will configure the root logger.

You will need to configure the two other loggers manually if you need their output to go elsewhere (or maybe configure a "routing" handler on the root logger).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.