This question already has an answer here:
- Python: logging module - globally 4 answers
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?
A module has by default only access to builtin functions and builtin constants. For all other variables, functions... you have to use the keyword
import
.Now for your concrete example, you can import the
log
-variable ofmoduleA
inmodulesB
like this:The following would be equivalent because the logging-module returns the same instance of the logger that was returned to
moduleA
:Another solution for you could be to use the default-logger of the logging module like this:
You could make your own logging "module" which instantiates the logger, than have all of your code import that instead. Think:
logger.py:
codeA.py:
codeB.py:
Creating a global logger which can be used to
Create a module called called myLogger.py : This will have the log creation code
myLogger.py:
Now to create a new log in your module say A.py
Thus you have to pass the file name along while getting the logger.
To use the global logger in A.py:
Need not pass the file name in this case as we gonna use the global log.