In my Flask application I have implemented a logging system using the logging library. It is currently run in a function below:
if __name__ == "__main__":
    """[Runs the webserver.
    Finally block is used for some logging management. It will first shut down
    logging, to ensure no files are open, then renames the file to 'log_'
    + the current date, and finally moves the file to the /logs archive
    directory]
    """
    try:
        session_management.clean_uploads_on_start(UPLOAD_FOLDER)
        app.run(debug=False)
    finally:
        try:
            logging.shutdown()
            new_log_file_name = log_management.rename_log(app.config['DEFAULT_LOG_NAME'])
            log_management.move_log(new_log_file_name)
        except FileNotFoundError:
            logging.warning("Current log file not found")
        except PermissionError:
            logging.warning("Permissions lacking to rename or move log.")
I discovered that the file is not renamed and moved if (either) the cmd prompt is force closed, or if the server crashes. I thought it might be better to put the rename and move into the initial 'try' block of the function, prior to the server starting, but I run into issues because I have a config file (which is imported in this script) which has the following code:
logging.basicConfig(filename='current_log.log', level=logging.INFO,
                    filemode='a',
                    format='%(asctime)s:%(levelname)s:%(message)s')
I have tried to do something like the below, but I still run into permission errors, but I think I am still running into errors because the log_management script also imports config. Further, I could not find a function which starts the logging system similar to logging.shutdown() which is used upon the system ending, otherwise I would shut it down, move the file (if it exists) and the start it back up.
  try:
        session_management.clean_uploads_on_start(UPLOAD_FOLDER)
        log_management.check_log_on_startup(app.config['DEFAULT_LOG_NAME'])
        import config
        app.run(debug=False)
    finally:
        try:
            logging.shutdown()
            new_log_file_name = log_management.rename_log(app.config['DEFAULT_LOG_NAME'])
            log_management.move_log(new_log_file_name)
        except FileNotFoundError:
            logging.warning("Current log file not found")
        except PermissionError:
            logging.warning("Permissions lacking to rename or move log.")
# (in another script)
def check_log_on_startup(file_name):
    if os.path.exists(file_name):
        move_log(rename_log(file_name))
Any suggestions much welcomed, because I feel like I'm at a brick wall!