MFB MFB - 13 days ago 6
Python Question

Python global logging

How do I make a Logger global so that I can use it in every module I make?

Something like this in moduleA:

import logging
import moduleB

log = logging.getLogger('')

result = moduleB.goFigure(5)
log.info('Answer was', result)


With this in moduleB:

def goFigure(integer):
if not isinstance(integer, int):
log.critical('not an integer')
else:
return integer + 1


Currently, I will get an error because moduleB does not know what
log
is. How do I get around that?

Answer

You could make your own logging "module" which instantiates the logger, than have all of your code import that instead. Think:

logger.py:

import logging
log = logging.getLogger('')

codeA.py:

from logger import log
log.info('whatever')

codeB.py:

from logger import log
log.warn('some other thing')