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.

Log best-effort failures instead of dropping them

Juan Denisc1f909b96613
diff --git a/backend/app/services/backup_service.py b/backend/app/services/backup_service.py
index 6fd8c6c4..3f30ef40 100644
--- a/backend/app/services/backup_service.py
+++ b/backend/app/services/backup_service.py
@@ -1107,7 +1107,9 @@ class BackupService:
'message': f'Backup {status}: {backup_name}' + (f' — {message}' if message else ''),
}])
except Exception:
- pass
+ # Never break the backup flow over an alert, but a lost "backup
+ # failed" alert must at least reach the log.
+ logger.exception('Could not send the backup notification for %s', backup_name)
@staticmethod
def _format_size(size: int) -> str:
diff --git a/backend/app/services/build_service.py b/backend/app/services/build_service.py
index 69121697..3c621089 100644
--- a/backend/app/services/build_service.py
+++ b/backend/app/services/build_service.py
@@ -10,6 +10,7 @@ Supports:
- Build timeout handling
"""
+import logging
import os
import subprocess
@@ -26,6 +27,8 @@ from pathlib import Path
from app import paths
from app.utils.config_store import load_json_config
+logger = logging.getLogger(__name__)
+
class BuildService:
"""Service for building applications from source code."""
@@ -700,7 +703,9 @@ class BuildService:
with open(filepath, 'w') as f:
json.dump(build_log, f, indent=2)
except Exception:
- pass
+ # The build itself is done; losing its log should not fail it,
+ # but it should not vanish without a trace either.
+ logger.exception('Could not save the build log for app %s', app_id)
@classmethod
def _update_build_stats(cls, app_id: int) -> None:
diff --git a/backend/app/services/manifest_apply_service.py b/backend/app/services/manifest_apply_service.py
index fe07defa..f794e415 100644
--- a/backend/app/services/manifest_apply_service.py
+++ b/backend/app/services/manifest_apply_service.py
@@ -9,6 +9,7 @@ Phase 5 adds fleet targeting.
idempotent — a second plan against a just-applied manifest is empty.
"""
+import logging
import uuid
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
@@ -23,6 +24,8 @@ from app.models.environment import Environment
from app.models.managed_database import ManagedDatabase
from app.models.project import Project
+logger = logging.getLogger(__name__)
+
# manifest backup schedule -> cron
_SCHEDULE_CRON = {
@@ -1217,7 +1220,9 @@ class ManifestApplyService:
job_id=job.id, step_index=idx, level=level, message=message,
data=json.dumps(data) if data else None))
except Exception:
- pass
+ # The step still ran; record that its log line is missing.
+ logger.warning('Could not write deploy log line for job %s step %s',
+ job.id, idx, exc_info=True)
# -- helpers ------------------------------------------------------------
diff --git a/backend/app/services/run_log_service.py b/backend/app/services/run_log_service.py
index 2fb0e029..fb9e1c1b 100644
--- a/backend/app/services/run_log_service.py
+++ b/backend/app/services/run_log_service.py
@@ -27,6 +27,7 @@ never breaks logging.
"""
import json
+import logging
import re
import time
from collections import deque
@@ -36,6 +37,17 @@ from typing import Any, Callable, List, Optional
from app import db
from app.models.deployment_job import DeploymentJob, DeploymentJobLog
+logger = logging.getLogger(__name__)
+_reported = set()
+
+
+def _report_once(key: str, message: str) -> None:
+ # Live emits run per flush; a broken socket path would flood the log.
+ # Once per kind is enough to make "live logs stopped" findable.
+ if key not in _reported:
+ _reported.add(key)
+ logger.warning(message, exc_info=True)
+
# ---------------------------------------------------------------------------
# Sanitation (D5): strip ANSI escapes, resolve `\r` progress overwrites. We keep
@@ -116,7 +128,7 @@ def _make_default_emit_log(run_kind: str) -> Callable:
from app.sockets import emit_run_log
emit_run_log(run_kind, run_id, lines)
except Exception:
- pass
+ _report_once(f'log:{run_kind}', f'Live {run_kind} log emit failed')
return _emit
@@ -126,7 +138,7 @@ def _make_default_emit_status(run_kind: str) -> Callable:
from app.sockets import emit_run_status
emit_run_status(run_kind, run_id, status)
except Exception:
- pass
+ _report_once(f'status:{run_kind}', f'Live {run_kind} status emit failed')
return _emit
@@ -339,7 +351,7 @@ class RunLogStream:
try:
self._emit_log(self.job.id, lines)
except Exception:
- pass
+ _report_once(f'emit:{type(self).__name__}', 'Run log emitter raised')
except Exception:
# Buffered-drop on flush failure (D10): one telemetry event, then
# continue. A stuck deployment is worse than a missing log line.
diff --git a/backend/tests/test_best_effort_failures_logged.py b/backend/tests/test_best_effort_failures_logged.py
new file mode 100644
index 00000000..1444a3e0
--- /dev/null
+++ b/backend/tests/test_best_effort_failures_logged.py
@@ -0,0 +1,45 @@
+"""Best-effort side effects may fail, but never silently.
+
+Each of these was `except Exception: pass`: a lost "backup failed" alert,
+a broken live deploy log (dead for the life of the process) and a missing
+deploy log line all left no trace. They still must not raise.
+"""
+import logging
+from unittest.mock import patch
+
+from app.services import run_log_service
+from app.services.backup_service import BackupService
+
+
+def test_lost_backup_alert_is_logged_not_raised(app, caplog, monkeypatch):
+ monkeypatch.setattr(BackupService, 'get_config', classmethod(
+ lambda cls: {'notifications': {'on_failure': True}}))
+ with patch('app.services.notification_service.NotificationService.send_all',
+ side_effect=RuntimeError('bus down')), \
+ caplog.at_level(logging.ERROR, logger='app.services.backup_service'):
+ BackupService._send_backup_notification('Nightly', False, 'disk full')
+ assert 'Could not send the backup notification for Nightly' in caplog.text
+ assert 'bus down' in caplog.text
+
+
+def test_broken_live_log_emit_is_reported_once(caplog, monkeypatch):
+ monkeypatch.setattr(run_log_service, '_reported', set())
+ emit = run_log_service._make_default_emit_log('deploy')
+ with patch('app.sockets.emit_run_log', side_effect=RuntimeError('socket gone')), \
+ caplog.at_level(logging.WARNING, logger='app.services.run_log_service'):
+ for _ in range(5):
+ emit('run-1', [{'message': 'x'}])
+ assert caplog.text.count('Live deploy log emit failed') == 1
+
+
+def test_missing_deploy_log_line_is_logged_not_raised(app, caplog):
+ from app.services.manifest_apply_service import ManifestApplyService
+
+ class Job:
+ id = 42
+
+ with patch('app.services.manifest_apply_service.db.session.begin_nested',
+ side_effect=RuntimeError('locked')), \
+ caplog.at_level(logging.WARNING, logger='app.services.manifest_apply_service'):
+ ManifestApplyService._log(Job(), 3, 'info', 'step done')
+ assert 'Could not write deploy log line for job 42 step 3' in caplog.text