33
44from flask import Flask , jsonify , request
55from flask_cors import CORS
6+ from werkzeug .exceptions import HTTPException
67
7- from config .settings import Config , limiter
8+ from config .logging import setup_logging
9+ from config .ratelimit import limiter
10+ from config .settings import Config
811from routes import register_routes
912from utility .database import extract_error_message
1013
1114app = Flask (__name__ )
1215app .config .from_object (Config )
1316CORS (app )
1417limiter .init_app (app )
18+ logger = setup_logging ()
1519
1620if app .config ["TESTING" ]:
1721 limiter .enabled = False
@@ -26,16 +30,13 @@ def home():
2630register_routes (app )
2731
2832
29- # Add a status field to all JSON responses
3033@app .after_request
31- def add_status (response ):
32- if response .is_json :
33- original_data = response .get_json ()
34- new_response = {
35- "success" : response .status_code in range (200 , 300 ),
36- "data" : original_data if original_data != [] else None ,
37- }
38- response .set_data (jsonify (new_response ).data )
34+ def log_response (response ):
35+ sender = request .remote_addr
36+ method = request .method
37+ path = request .path
38+ status_code = response .status_code
39+ logger .info (f"{ sender } : { method } { path } { status_code } " )
3940 return response
4041
4142
@@ -47,6 +48,9 @@ def add_common_headers(response):
4748
4849@app .errorhandler (429 )
4950def ratelimit_error (e ):
51+ logger .warning (
52+ f"Rate limit exceeded: { request .method } { request .path } - { e .description } "
53+ )
5054 return (
5155 jsonify (
5256 error = "Too many requests" ,
@@ -59,20 +63,11 @@ def ratelimit_error(e):
5963
6064@app .errorhandler (Exception )
6165def handle_exception (e ):
62- # If the app is in debug mode, return the full traceback
63- if app .debug :
64- return (
65- jsonify (
66- error = "Internal Server Error" ,
67- message = str (e ),
68- type = type (e ).__name__ ,
69- url = request .url ,
70- traceback = traceback .format_exc ().splitlines (),
71- ),
72- 500 ,
73- )
74-
75- # Otherwise, return a more user-friendly error message
66+ if isinstance (e , HTTPException ):
67+ return e
68+
69+ trace = traceback .format_exc ().splitlines ()[- 1 ]
70+ logger .exception (f"An unhandled exception occurred: { trace } " )
7671 error_message = extract_error_message (str (e ))
7772 return jsonify (error = "Internal Server Error" , message = error_message ), 500
7873
@@ -84,4 +79,5 @@ def handle_exception(e):
8479 )
8580 args = parser .parse_args ()
8681
82+ logger .info ("Starting Flask application..." )
8783 app .run (host = "0.0.0.0" , port = 5000 , debug = args .debug )
0 commit comments