From 04a2f5a46b056b297e0e7865b297395fbf78c90c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Katariina=20J=C3=A4rvenm=C3=A4ki?= Date: Sun, 1 Mar 2026 14:12:44 +0200 Subject: [PATCH] Implemented logging configuration --- app/main.py | 20 ++++++++++++++++++-- app/test_main.py | 4 +--- urls.db | Bin 8192 -> 8192 bytes 3 files changed, 19 insertions(+), 5 deletions(-) diff --git a/app/main.py b/app/main.py index 2bb4b69..079aec0 100644 --- a/app/main.py +++ b/app/main.py @@ -1,20 +1,29 @@ from fastapi import FastAPI, HTTPException from fastapi.responses import RedirectResponse +from contextlib import asynccontextmanager from pydantic import BaseModel from app.utils import generate_short_code from dotenv import load_dotenv import os import sqlite3 -from contextlib import asynccontextmanager +import logging +# Set up logging configuration +logging.basicConfig(level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s") +logger = logging.getLogger(__name__) + +# Database connection setup @asynccontextmanager async def lifespan(app: FastAPI): conn = sqlite3.connect('urls.db') conn.execute('''CREATE TABLE IF NOT EXISTS urls (id INTEGER PRIMARY KEY, short_code TEXT, original_url TEXT, clicks INTEGER)''') conn.commit() + logger.info("Database initialized or already exists.") yield conn.close() + logger.info("Database connection closed.") app = FastAPI(lifespan=lifespan) @@ -27,10 +36,12 @@ class URLRequest(BaseModel): @app.get("/") def home(): + logger.info("Home endpoint accessed.") return {"message": "URL Shortener API"} @app.post("/shorten") def shorten_url(request: URLRequest): + logger.info(f"Request received to shorten URL: {request.url}") short_code = generate_short_code() conn = get_db_connection() @@ -42,14 +53,18 @@ def shorten_url(request: URLRequest): conn.commit() conn.close() - return {"short_url": f"{os.getenv('BASE_URL', 'http://localhost:8000')}/{short_code}"} + short_url = f"{os.getenv('BASE_URL', 'http://localhost:8000')}/{short_code}" + logger.info(f"Shortened URL created: {short_url}") + return {"short_url": short_url} @app.get("/{short_code}") def redirect_to_url(short_code: str): + logger.info(f"Redirect request received for short_code: {short_code}") conn = get_db_connection() url_data = conn.execute("SELECT original_url, clicks FROM urls WHERE short_code = ?", (short_code,)).fetchone() if url_data is None: + logger.warning(f"Shortened URL for {short_code} not found.") raise HTTPException(status_code=404, detail="Shortened URL not found") original_url, clicks = url_data @@ -57,4 +72,5 @@ def redirect_to_url(short_code: str): conn.commit() conn.close() + logger.info(f"Redirecting to {original_url}. Total clicks: {clicks + 1}") return RedirectResponse(url=original_url) \ No newline at end of file diff --git a/app/test_main.py b/app/test_main.py index 887e6aa..637d1ca 100644 --- a/app/test_main.py +++ b/app/test_main.py @@ -1,12 +1,10 @@ from fastapi.testclient import TestClient -from app.main import app import sys import os -# Add the 'app' folder to the sys.path sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) -from app.main import app # Now this should work correctly +from app.main import app client = TestClient(app) diff --git a/urls.db b/urls.db index d2b6c005ae31498604346bd01e199d77414a0961..b82e8dfeb508175ae411ce4025eb8a1b62399c3c 100644 GIT binary patch delta 105 zcmZp0XmFSy&B#Ad#+i|SW5N=C86LiF2L6ZqhxixsxA3R(yYZ{@bMU?7JH@w}uX|%* zHlMB>4=aPDF-L}9RY_!dMoCFQv6a4lYDHphK~Ab(a(=EXH&EV?!_~*V!YqICM0w%O Ir{zo;0W#$teE