wong2
wong2

Reputation: 35720

logging configs overwritten by others

this is my module:

# module.py
import logging

logging.basicConfig(filename='app.log')

logger = logging.getLogger(__name__) 

def method(x):
    logger.info('x is %s', x)
    return x + x

and my module is used by a third party script, the problem is that it did some logging setups which overwrite mine.

# main.py
import logging
from logging.config import dictConfig
from module import method

logger = logging.getLogger(__name__) 

def setup_loghandlers():
    dictConfig({
        "version": 1,
        "disable_existing_loggers": False,

        "handlers": {
            "console": {
                "level": "DEBUG",
                "class": "logging.StreamHandler"
            },
        },

        "root": {
            "handlers": ["console"],
            "level": "INFO",
        }
    })

setup_loghandlers()

y = method(20)
logger.info('y is %s', y)

now if I run main.py, I get all the logs in console, while what I actually need is module.py's logs go to app.log file

PS: I can't modify main.py, I can only modify my module.py

Upvotes: 0

Views: 426

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

Your module should not configure the logger itself (because it doesn't have enough knowledge of the execution context), it's the application / script using your module's responsability to do s. Think about what would happen with your module used by concurrent apps all trying to write to the same file at the same moment, or running running on a device with restricted disk space (or no disk space at all) etc...

To make a long story short: if you "can't modify main.py" then ask the owner of "main.py" to do so (in the way he sees fits) and give you access to whatever he configured if he wants you to be able to debug anything. If he don't then it's not your problem anymore.

Upvotes: 2

Related Questions