Skip to content

Instantly share code, notes, and snippets.

@mwestwood
Created September 8, 2023 23:55
Show Gist options
  • Save mwestwood/dc7fbf8212436a5f72b60cba2176ab41 to your computer and use it in GitHub Desktop.
Save mwestwood/dc7fbf8212436a5f72b60cba2176ab41 to your computer and use it in GitHub Desktop.
import logging
import os
import threading
from flask import Flask, jsonify
app = Flask(__name__)
# Create a lock to serialize access to the log file
log_file_lock = threading.Lock()
# Event to signal whether a request is in progress
request_in_progress_event = threading.Event()
@app.route('/')
def my_endpoint():
global request_in_progress_event
# Check if a request is already in progress
if request_in_progress_event.is_set():
return jsonify({"message": "A request is already in progress. Please try again later."})
# Set the event to indicate that a request is in progress
request_in_progress_event.set()
# Generate a unique log filename for this request, e.g., based on a timestamp or request ID
log_filename = f"my_log_{get_unique_id()}.log"
# Acquire the lock to prevent concurrent access to the log file
with log_file_lock:
# Check if the log file already exists
if os.path.exists(log_filename):
app.logger.warning("Log file already exists; skipping log creation.")
else:
# Create a new FileHandler for this request
file_handler = logging.FileHandler(log_filename)
# Configure the log format, level, and attach the handler to the logger
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.DEBUG)
app.logger.addHandler(file_handler)
# Log a message
app.logger.info("This log message will be written to a new file.")
# Remove the handler from the logger to prevent further writing
app.logger.removeHandler(file_handler)
# Close the handler to release the log file
file_handler.close()
# Now, you can safely read the log file without further writing
with open(log_filename, 'r') as file:
log_contents = file.read()
# Clear the event to indicate that the request has completed
request_in_progress_event.clear()
return "Request processed successfully."
if __name__ == '__main__':
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment