Zeno
Zeno

Reputation: 1829

Pass a Python ArgumentParser to another module?

I have this Python code in main.py:

parser = argparse.ArgumentParser()
parser.add_argument("subname", help="Name of subreddit")
args = parser.parse_args()

Then in another file speciallogger.py:

import logging
import time

from logging.handlers import TimedRotatingFileHandler
path='logs/log_SUBNAMEHERE_logger.txt'
logmsg = logging.getLogger("Rotating Log")
fmt = u'%(asctime)s\t%(levelname)s\t%(filename)s:%(lineno)d\t%(message)s'
logmsg.setLevel(logging.INFO)
handler = TimedRotatingFileHandler(path, when="d", interval=1, backupCount=14)
handler.setFormatter(logging.Formatter(fmt))
logmsg.addHandler(handler)

The script (starts with main.py) executes via a cron using an argument.

I need to pass that argument to speciallogger.py so I can name the filename what subname is, along with ensuring logmsg can be used across all modules without the log file being recreated each import during a script using multiple modules.

How can I do this?

Upvotes: 0

Views: 428

Answers (1)

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

Make a function in speciallogger.py and call that function right after doing the arg parsing.

speciallogger.py

import logging
import time
from logging.handlers import TimedRotatingFileHandler

def initialize(subname):
    path = f'logs/log_{subname}_logger.txt'
    logmsg = logging.getLogger("Rotating Log")
    fmt = u'%(asctime)s\t%(levelname)s\t%(filename)s:%(lineno)d\t%(message)s'
    logmsg.setLevel(logging.INFO)
    handler = TimedRotatingFileHandler(path, when="d", interval=1, backupCount=14)
    handler.setFormatter(logging.Formatter(fmt))
    logmsg.addHandler(handler)

main.py

import speciallogger
...
if __name__ == "__main__":
    ...
    parser = argparse.ArgumentParser()
    parser.add_argument("subname", help="Name of subreddit")
    args = parser.parse_args()
    speciallogger.initialize(args.subname)

logging.getLogger() will return the same logger object no matter where in the program it's called, per the documentation:

"All calls to this function with a given name return the same logger instance. This means that logger instances never need to be passed between different parts of an application."

Thus, when you modify it by doing setLevel and addHandler, you're making a persistent change that should reflect across the entire program.

Upvotes: 1

Related Questions