Alexandre Lemaitre
Alexandre Lemaitre

Reputation: 51

Logging module can't load the good configuration

I don't know how to use a different logging config when my module A is imported by my module B, but with another logging configuration. Any ideas on how to resolve this?

Module A code:

logging.basicConfig(filename="/var/log/ModuleA",format="%(asctime)s %(message)s",datefmt="%d/%m/%Y %H:%M:%S")
log=logging.getLogger(__name__)
logging.Formatter.converter = time.gmtime
logging.setLevel(logging.DEBUG)

Module B code:

import ModuleA      
logging.basicConfig(filename="/var/log/ModuleB",format="%(asctime)s %(message)s",datefmt="%d/%m/%Y %H:%M:%S")                                                                                                                                                                                          log=logging.getLogger(__name__)
logging.Formatter.converter = time.gmtime
logging.setLevel(logging.DEBUG)

Upvotes: 0

Views: 166

Answers (1)

AKX
AKX

Reputation: 169051

basicConfig can only be run once per process (or, well, when the root logger has no configuration).

If you want different modules to log into different places, you'll have to configure their loggers accordingly – and preferably, do that in the application code that imports the modules, not in the modules themselves. It's not their concern to define where their log output goes.

For instance, you could use the dictConfig API to configure two named loggers, module1 and module2, and handlers and formatters for them:

import logging
from logging.config import dictConfig

dictConfig(
    {
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {"my_format": {"format": "%(asctime)s %(message)s", "datefmt": "%d/%m/%Y %H:%M:%S",},},
        "handlers": {
            "file_a": {"level": "INFO", "class": "logging.FileHandler", "filename": "a.log", "formatter": "my_format",},
            "file_b": {"level": "INFO", "class": "logging.FileHandler", "filename": "b.log", "formatter": "my_format",},
        },
        "loggers": {
            "module1": {"handlers": ["file_a"], "level": "INFO", "propagate": False,},
            "module2": {"handlers": ["file_b"], "level": "INFO", "propagate": False,},
        },
    }
)

Then, pretending these are in module1 and module2:

log1 = logging.getLogger("module1")
log1.info("Hello")
log2 = logging.getLogger("module2")
log2.info("World")

you'd end up with Hello in a.log and World in b.log.

Upvotes: 1

Related Questions