From f0d5852390da11972cc674735f548fcb63fe8335 Mon Sep 17 00:00:00 2001 From: vista-man <524715@vistacollege.nl> Date: Mon, 27 Jan 2025 20:54:03 +0100 Subject: [PATCH] Improve weather API logging format and enhance stdout redirection for better logging --- Python/api/api.py | 11 ++++++----- Python/api/weather.log | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/Python/api/api.py b/Python/api/api.py index bb3c251..da46882 100644 --- a/Python/api/api.py +++ b/Python/api/api.py @@ -64,7 +64,7 @@ def get_weather(lat, lon, city_name): if response.status_code == 200: data = response.json() # Parse the JSON response # Print the weather information - print(f"Weather at coordinates ({lat}, {lon}) for city {city_name}:") + print(f"Weather at coordinates ({lat}, {lon}) in {city_name}:") print(f"Temperature: {data['main']['temp']}°C") print(f"Weather: {data['weather'][0]['description']}") else: @@ -76,15 +76,16 @@ if __name__ == "__main__": log_file_path = os.path.join(os.path.dirname(__file__), 'weather.log') if os.path.exists(log_file_path): with open(log_file_path, 'a') as log_file: - log_file.write('\n\n') # Add 2 empty lines before appending new logs + log_file.write('\n') # Add 2 empty lines before appending new logs with open(log_file_path, 'a') as log_file: - tee = Tee(sys.stdout, log_file) - sys.stdout = tee city_name = input("Enter city name: ") # Prompt the user to enter a city name lat, lon = get_coordinates(city_name) # Get the coordinates of the city if lat is not None and lon is not None: - print(f"Coordinates for {city_name}: ({lat}, {lon})") # Log the coordinates and city name + original_stdout = sys.stdout # Save the original stdout + tee = Tee(original_stdout, log_file) + sys.stdout = tee # Redirect stdout to both terminal and log file get_weather(lat, lon, city_name) # Get the weather data for the coordinates + sys.stdout = original_stdout # Reset stdout to original # Sleep for 5 seconds before exiting to ensure all logs are written time.sleep(5) tee.close() # Close the Tee object to ensure all files are properly closed \ No newline at end of file diff --git a/Python/api/weather.log b/Python/api/weather.log index e69de29..f0b2c1c 100644 --- a/Python/api/weather.log +++ b/Python/api/weather.log @@ -0,0 +1,19 @@ +Weather at coordinates (50.8184796, 6.0065275) in Bocholtz: +Temperature: 7.67�C +Weather: moderate rain + +Weather at coordinates (50.87489555, 6.05938669638836) in Kerkrade: +Temperature: 8.4�C +Weather: moderate rain + +Weather at coordinates (50.8876735, 5.9773285) in Heerlen: +Temperature: 8.18�C +Weather: light rain + +Weather at coordinates (50.8876735, 5.9773285) in Heerlen: +Temperature: 8.18°C +Weather: light rain + +Weather at coordinates (52.07168255, 5.745510631034939) in ede: +Temperature: 8.48°C +Weather: light rain