Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwriting python log config

I want to use an external module but this module configures the logger and I don't know how to overwrite it in order to log to file

#my main.py
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
logging.basicConfig(filename='/home/pi/thermostat/server.log',level=logging.DEBUG)
logging.basicConfig(format='%(asctime)s %(message)s')
logger = logging.getLogger(__name__)    

termo = SHT1x(dataPin, clkPin, SHT1x.GPIO_BOARD) #this one configures the log also

def main():
    logger.info("SERVER START")
    return

if __name__ == "__main__":
    main()

And the module i am using is doing:

#SHT1x module
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(____name____)

def main():
    #....

if __name__ == '__main__':
    main()

So my program is logging to console not to server.log Is there a way to overwrite this behavior?

like image 911
AdrianS Avatar asked Nov 02 '25 07:11

AdrianS


1 Answers

Modules should not be calling logging.basicConfig. Only the main program should call basicConfig once, if at all. Per the docs, basicConfig does nothing if the root logger already has handlers configured.

If you can not modify the SHT1x module, then as a workaround, you could arrange for main.py to call its logging.basicConfig before importing SHT1x. The basicConfig call that executes first will be the only one that affects logging.

def main():
    import SHT1x
    logger.info("SERVER START")
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    termo = SHT1x.somefunction(dataPin, clkPin, SHT1x.GPIO_BOARD) #this one configures the log also


if __name__ == "__main__":
    import logging
    logging.basicConfig(filename='/home/pi/thermostat/server.log',
                        level=logging.DEBUG,
                        format='%(asctime)s %(message)s')
    logger = logging.getLogger(__name__)    
    
    main()

Note: I've modified my first suggestion so main.py calls logging.basicConfig inside the if __name__== "__main__" suite. This preserves your ability to use main.py as both a script and a module.

like image 60
unutbu Avatar answered Nov 03 '25 22:11

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!