I like the python logging infrastructure and I want to use it for a number of different overnight jobs that I run. A lot of these jobs use module X let's say. I want the logging for module X to write to a log file not dependent on module X, but based on the job that ultimately led to calling functionality in module X.
So if overnight_script_1.py calls foo() in module X, I want the log of foo() to go to overnight_script_1.log. I also want overnight_script_2.py's call of foo() to log to overnight_script_2.log.
A potential solution to this problem would be to set up the log file based on looking at the 0th argument to sys.argv which can be mapped to my preferred file. Something seems hacky about doing it this way. Is there a preferred design pattern for doing this? I don't want to rummage through different log files based on the module where the function was called to find my diagnostic information for one of my scripts. Here is some code because I am not sure I am making myself clear.
Here is script1.py
import X
import logging_utils as lu
import sys
logname=sys.argv[0][:-3] # logname==script1 with the .py cut off
logger=lu.setup_logger(log_name) # assume this does the formatting and sets the filehandlers
# furthermore assume the file handler is set so that the output goes to script1.log.
# do a bunch of thing
logger.info('I am doing a bunch of things in script1 and I will now call X.foo()')
X.foo() # see module X below
logger.info('I finished X.foo()')
Similary, here is script2.py
import X
import logging_utils as lu
import sys
logname=sys.argv[0][:-3] # logname==script2 with the .py cut off
logger=lu.setup_logger(log_name) # assume this does the formatting and sets the filehandlers
# furthermore assume the file handler is set so that the output goes to script2.log.
# do a bunch of thing
logger.info('I am doing a bunch of things in script2 and I will now call X.foo()')
X.foo() # see module X below
logger.info('I finished X.foo()')
Here is X.py
import logging
import sys
logname=sys.argv[0][:-3] # could be script1 or script2
logger=logging.getLogger(logname)
def foo():
try:
i=1/0
except:
logger.error('oops - division by zero')
Then I want to run:
python script1.py
python script2.py
and get two log files script1.log and script2.log where the division by zero error that occurred in module X is logged in each.
logging.basicConfig()with the appropriate arguments. Where and how are you setting up logging handlers, formatters etc... currently?Xmodulo should not define any handler. The scripts are responsible for defining the handlers (either to a file, or to the console), set the level for logging and add the handlers to the logger... so the standard configuration already completely addresses the situation you are describing.xat all. You define handlers only in your scripts.