Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(api): global error handlers and a real logging configuration

Juan Denis153ba83fc6e1
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index 2bc3cca7..41d7ae52 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -1,6 +1,7 @@
import os
import sys
from flask import Flask, send_from_directory, request, jsonify
+from werkzeug.exceptions import HTTPException
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager
from flask_cors import CORS
@@ -27,6 +28,57 @@ socketio = None
FRONTEND_DIST = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'frontend', 'dist')
+# Set once per process: create_app() runs many times in a test session and
+# gunicorn imports the module before forking, so an unguarded addHandler would
+# duplicate every log line N times.
+_logging_configured = False
+
+
+def _configure_logging(app):
+ """Give the app a real logging setup.
+
+ Services across the codebase call ``logging.getLogger(__name__).warning(...)``
+ but nothing ever configured the root logger, so those records fell through to
+ logging's last-resort handler: WARNING and above only, no timestamp, no
+ logger name, INFO dropped on the floor. That is why a panel that was failing
+ to serve its own agent installer (issue #101) produced no diagnostic trail at
+ all. ``LOG_LEVEL`` overrides the default.
+ """
+ global _logging_configured
+
+ import logging
+
+ level_name = os.environ.get('LOG_LEVEL', '').upper()
+ if level_name and hasattr(logging, level_name):
+ level = getattr(logging, level_name)
+ elif app.config.get('TESTING'):
+ # TestingConfig sets DEBUG=True, so keying off DEBUG alone would move the
+ # whole test suite to DEBUG logging as a side effect of adding a handler.
+ level = logging.INFO
+ else:
+ level = logging.DEBUG if app.config.get('DEBUG') else logging.INFO
+
+ from flask.logging import default_handler
+
+ root = logging.getLogger()
+ root.setLevel(level)
+ app.logger.setLevel(level)
+
+ # Flask attaches its own handler to app.logger, which ALSO propagates to the
+ # root logger. Leaving both in place prints every app.logger record twice --
+ # once as Flask's `%(module)s` and once as ours as `%(name)s`. Drop Flask's
+ # and let the single root handler below own the output.
+ app.logger.removeHandler(default_handler)
+
+ if not _logging_configured:
+ handler = logging.StreamHandler(sys.stderr)
+ handler.setFormatter(logging.Formatter(
+ '[%(asctime)s] %(levelname)s in %(name)s: %(message)s'
+ ))
+ root.addHandler(handler)
+ _logging_configured = True
+
+
def create_app(config_name=None):
global socketio
@@ -41,6 +93,8 @@ def create_app(config_name=None):
)
app.config.from_object(config[config_name])
+ _configure_logging(app)
+
# Trust the reverse proxy's forwarding headers to derive the real client IP
# (config-gated; default off). ProxyFix rewrites request.remote_addr from the
# rightmost TRUSTED_PROXY_HOPS entries of X-Forwarded-For — the hops our own
@@ -819,6 +873,35 @@ def create_app(config_name=None):
return send_from_directory(app.static_folder, 'index.html')
return {'message': 'ServerKit API is running', 'docs': '/api/v1/'}, 200
+ # Unhandled exceptions. Flask only routes here when it is not propagating
+ # (so pytest and the dev server still re-raise with a full traceback);
+ # in production this is the difference between a logged, JSON-shaped 500 and
+ # a silent Werkzeug HTML page returned to an API client that wanted JSON.
+ @app.errorhandler(500)
+ def internal_error(e):
+ original = getattr(e, 'original_exception', None)
+ app.logger.exception(
+ 'Unhandled exception on %s %s', request.method, request.path,
+ exc_info=original or e
+ )
+ # JSON either way: unlike a 404, there is no sensible SPA fallback for a
+ # crash, and an HTML page tells the caller nothing it can act on.
+ return {'error': 'Internal server error'}, 500
+
+ # Framework-generated HTTP errors (abort(), 405 from the router, 413 from
+ # MAX_CONTENT_LENGTH) rendered Werkzeug's HTML page even under /api/, so an
+ # API client parsing JSON got a parse error instead of the real reason.
+ # The more specific 404/500 handlers above still win for those codes.
+ @app.errorhandler(HTTPException)
+ def http_exception(e):
+ if request.path.startswith('/api/'):
+ app.logger.warning(
+ 'HTTP %s on %s %s: %s', e.code, request.method, request.path, e.description
+ )
+ return {'error': e.description or e.name, 'status': e.code}, e.code
+ # Non-API paths keep Werkzeug's standard HTML error page.
+ return e.get_response()
+
# Catch-all route for SPA - must be after all other routes
@app.errorhandler(404)
def not_found(e):
diff --git a/backend/tests/test_api_error_shape.py b/backend/tests/test_api_error_shape.py
new file mode 100644
index 00000000..4a3394d2
--- /dev/null
+++ b/backend/tests/test_api_error_shape.py
@@ -0,0 +1,110 @@
+"""API error-response shape and logging configuration.
+
+Issue #101 was hard to diagnose partly because the panel produced no diagnostic
+trail at all: the backend had exactly one error handler (the 404/SPA one), no
+500 or HTTPException handler, and nothing anywhere configured logging -- so
+framework-generated errors under /api/ came back as Werkzeug HTML to clients
+parsing JSON, and unhandled exceptions were never logged with their path.
+"""
+
+import logging
+
+from werkzeug.exceptions import InternalServerError
+
+
+def test_unknown_api_route_returns_json_404(client):
+ response = client.get('/api/v1/this-route-does-not-exist')
+
+ assert response.status_code == 404
+ assert response.is_json
+ assert response.get_json()['error'] == 'Not found'
+
+
+def test_method_not_allowed_on_api_returns_json_not_html(client):
+ """405 used to render Werkzeug's HTML page even under /api/.
+
+ An API client parsing the body got a JSON decode error instead of the
+ actual reason it failed.
+ """
+ # The installer route is GET-only and needs no auth, so a POST reaches the
+ # router's 405 without any credential handling in the way.
+ response = client.post('/api/v1/servers/install.sh')
+
+ assert response.status_code == 405
+ assert response.is_json, (
+ f'405 under /api/ returned {response.content_type}; API clients parse JSON'
+ )
+ payload = response.get_json()
+ assert payload['status'] == 405
+ assert payload['error']
+
+
+def test_non_api_404_is_not_forced_into_json(client):
+ """The SPA fallback must survive the new HTTPException handler.
+
+ A more general handler that shadowed the 404 one would break client-side
+ routing for every deep link.
+ """
+ response = client.get('/some/spa/deep/link')
+
+ assert response.status_code in (200, 404)
+ if response.status_code == 200:
+ assert b'<' in response.get_data() # index.html, not a JSON error
+
+
+def test_internal_error_handler_is_registered(app):
+ """A 500 handler must exist, or API clients get an HTML page on a crash."""
+ handlers = app.error_handler_spec[None]
+
+ assert 500 in handlers and handlers[500], (
+ 'no 500 error handler registered; an unhandled exception returns '
+ "Werkzeug's HTML page and is never logged with its request path"
+ )
+ assert InternalServerError in handlers[500]
+
+
+def test_logging_is_configured_with_a_formatter(app):
+ """Services log via logging.getLogger(__name__); something must configure it.
+
+ Without a root handler those records fall through to logging's last-resort
+ handler: WARNING and above only, no timestamp, no logger name, INFO dropped.
+ """
+ root = logging.getLogger()
+
+ assert root.handlers, 'root logger has no handler; log records are unformatted'
+ assert any(h.formatter is not None for h in root.handlers), (
+ 'no handler has a formatter; records lose their timestamp and logger name'
+ )
+ assert root.level <= logging.INFO, (
+ f'root log level is {logging.getLevelName(root.level)}; INFO diagnostics '
+ f'never reach the operator'
+ )
+
+
+def test_logging_is_not_duplicated(app):
+ """Every record must be emitted once.
+
+ Flask attaches its own handler to app.logger, which also propagates to the
+ root logger. With a root handler added and Flask's left in place, every line
+ printed twice -- once formatted with %(module)s and once with %(name)s --
+ which is how it looked in the container before this was fixed.
+ """
+ from flask.logging import default_handler
+
+ assert default_handler not in app.logger.handlers, (
+ "Flask's default handler is still on app.logger while a root handler "
+ 'exists; every app.logger record is printed twice'
+ )
+
+ # And configuring twice must not stack a second handler. create_app() runs
+ # many times in a test session, and gunicorn imports the module before
+ # forking, so an unguarded addHandler would multiply every line.
+ from app import _configure_logging
+
+ root = logging.getLogger()
+ before = len(root.handlers)
+ _configure_logging(app)
+ assert len(root.handlers) == before, (
+ 'a repeat _configure_logging() added another root handler; every record '
+ 'would print once per call'
+ )