From 3652a3b98a9e5913bc5d50b3f1a7395884611e09 Mon Sep 17 00:00:00 2001 From: Steve Dogiakos Date: Tue, 1 Apr 2025 18:03:33 -0600 Subject: [PATCH] Add basic logging - Configure Python logging at INFO level. - Log key events: database initialization, incoming requests, validation errors, and successful guest submissions. - Log the number of guest entries displayed when rendering the page. This improves observability and helps with troubleshooting. --- app.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/app.py b/app.py index a237dc5..96393ee 100644 --- a/app.py +++ b/app.py @@ -1,6 +1,11 @@ from flask import Flask, render_template, request, redirect, url_for import sqlite3 import re +import logging + +# Set up basic logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) app = Flask(__name__) DATABASE = 'guestbook.db' @@ -20,6 +25,7 @@ def init_db(): ''') conn.commit() conn.close() + logger.info("Database initialized.") def is_valid_email(email): # A simple regex for basic email validation @@ -30,6 +36,7 @@ def is_valid_email(email): def index(): error = None if request.method == 'POST': + logger.info("Received POST request with form data.") first_name = request.form.get('first_name', '').strip() last_name = request.form.get('last_name', '').strip() email = request.form.get('email', '').strip() @@ -38,8 +45,10 @@ def index(): # Basic validation checks if not (first_name and last_name and email and location): error = "All fields are required." + logger.warning("Validation error: Missing required fields.") elif not is_valid_email(email): error = "Invalid email address." + logger.warning("Validation error: Invalid email address '%s'.", email) if error: # Retrieve guest entries to display on the page. @@ -50,7 +59,7 @@ def index(): conn.close() return render_template('index.html', error=error, guests=guests) - # If all validations pass, insert the data into the database. + # If validations pass, insert the data into the database. conn = sqlite3.connect(DATABASE) c = conn.cursor() c.execute( @@ -59,6 +68,7 @@ def index(): ) conn.commit() conn.close() + logger.info("New guest entry added: %s from %s.", first_name, location) return redirect(url_for('index')) # For GET requests, retrieve guest entries to display. @@ -67,8 +77,10 @@ def index(): c.execute('SELECT first_name, location FROM guests ORDER BY id DESC') guests = c.fetchall() conn.close() + logger.info("Rendering guestbook page with %d entries.", len(guests)) return render_template('index.html', error=error, guests=guests) if __name__ == '__main__': init_db() + logger.info("Starting Flask app on host 0.0.0.0, port 5000.") app.run(host='0.0.0.0', port=5000)