Search code examples
pythonfiledynamiciomodular

Python, Keeping a dynamically named file open in a large modular program


I am trying to create a logfile for a large modular program. The name is dynamically produced with a timestamp and I can't think of a good way to pass the open filename other than to make it a global variable:

import time

def CreateLogFile():
    timestr = time.strftime("%Y%m%d-%H%M%S")
    global LogFile
    filenamestring = timestr + 'LogFile.txt'
    LogFile = open('PrintLogs/' + filenamestring, 'w')

CreateLogFile()

This isn't working well and I was wondering if anyone had a better suggestion. Thanks


Solution

  • Just make your own logging module:

    import mylogger
    
    log_file_handle = mylogger.get_log()
    

    The get method can (should) handle all the logic of creating a new logfile if you haven't made one yet, or returning a handle to the already-created-this-session one.