Deffo
Deffo

Reputation: 207

Python logging module always uses the same file

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

Upvotes: 2

Views: 923

Answers (2)

Klaus D.
Klaus D.

Reputation: 14379

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.

Upvotes: 4

AKX
AKX

Reputation: 169338

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).

Upvotes: 1

Related Questions