0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I've tried this, but in main.py it gives the error NameError: name 'logging' is not defined. How am I meant to log lines in main.py?
@Zeno you would log things the same way as before. Import logging and use it as normal (call getLogger("Rotating Log") to make sure that you're using the same logger you modified during initialization).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.