Reputation: 742
In my Python script, I have a logger defined as follows:
RUN_LOG_BASE_DIR='/tmp/'
RUN_LOG_FILE_NAME = 'process_cc_log.txt'
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
runlog_formatter = logging.Formatter('%(asctime)s %(name)s line-%(lineno)d\t\t%(levelname)s\t%(message)s')
runlog_handler = logging.handlers.TimedRotatingFileHandler(os.path.join(RUN_LOG_BASE_DIR,
RUN_LOG_FILE_NAME), when='midnight', backupCount=30)
runlog_handler.setLevel(logging.DEBUG)
runlog_handler.setFormatter(runlog_formatter)
logger.addhandler(runlog_handler)
I tried passing in the RUN_LOG_BASE_DIR as an argument(/logs) to the main function, but it still writes to the /tmp directory.
main:
if __name__ == '__main__':
RUN_LOG_BASE_DIR = sys.argv[1]
How do I pass the base directory as an argument?
Upvotes: 0
Views: 502
Reputation: 2409
This is most likely because the code where you set up the logger runs before the if __name__ == '__main__
.
For example
MY_STRING = "hello"
print(MY_STRING)
if __name__ == '__main__':
MY_STRING = "goodbye"
The above code will always print hello
, because the print statement is run before the if
check.
However, if this was written as
def print_string(s):
print(s)
if __name__ == "__main__":
print("goodbye")
Then the program would accurately print out "goodbye".
A similar concept can be applied to your problem. Move your logging setup code inside a function, and then call the function with your desired logging dir.
Upvotes: 1