Spaces:
Running

axeronis commited on
Commit
f5c6732
Β·
1 Parent(s): f7bc54e

fix: exhaustive startup debugging and logging

Browse files
Files changed (1) hide show
  1. backend/start.py +48 -21
backend/start.py CHANGED
@@ -4,58 +4,85 @@ import sys
4
  import logging
5
  import time
6
 
7
- # Configure logging to stdout
8
  logging.basicConfig(
9
  level=logging.INFO,
10
- format='%(asctime)s - %(levelname)s - %(message)s',
11
  handlers=[logging.StreamHandler(sys.stdout)]
12
  )
13
  logger = logging.getLogger(__name__)
14
 
15
  def run_command(command, shell=True):
16
- logger.info(f"Running command: {command}")
17
  try:
18
- # Check if alembic exists in path
19
- subprocess.check_call(command, shell=shell)
 
 
 
 
 
 
20
  except subprocess.CalledProcessError as e:
21
  logger.error(f"❌ Command failed with exit code {e.returncode}")
22
- # Wait a bit to ensure logs are flushed before exiting container
23
- time.sleep(2)
24
  sys.exit(e.returncode)
25
 
26
  def main():
27
- logger.info("πŸš€ Starting MicroFunnel Backend (Python Startup Script)")
28
- logger.info(f"πŸ“‚ Working Directory: {os.getcwd()}")
 
 
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  # 1. Run Migrations
31
  logger.info("πŸ› οΈ Running Database Migrations...")
32
- # Explicitly call python -m alembic to avoid path issues
33
  run_command("python -m alembic upgrade head")
34
- logger.info("βœ… Migrations applied successfully.")
35
 
36
  # 2. Start Uvicorn
37
  host = "0.0.0.0"
38
  port = os.environ.get("PORT", "8000")
39
- logger.info(f"πŸ”Œ Starting Uvicorn on {host}:{port}")
40
 
41
- # Build uvicorn command
42
  uvicorn_cmd = [
43
  "python", "-m", "uvicorn",
44
  "app.main:app",
45
  "--host", host,
46
  "--port", port,
47
- "--log-level", "info"
48
  ]
49
 
50
- logger.info(f"Executing: {' '.join(uvicorn_cmd)}")
51
-
52
- # Flush buffers
53
  sys.stdout.flush()
54
- sys.stderr.flush()
55
 
56
- # Replace current process with uvicorn
57
- # This keeps PID 1 for signal handling (if this script ran as PID 1)
58
- os.execvp("python", uvicorn_cmd)
 
 
 
 
 
 
 
 
59
 
60
  if __name__ == "__main__":
61
  main()
 
4
  import logging
5
  import time
6
 
7
+ # Configure logging
8
  logging.basicConfig(
9
  level=logging.INFO,
10
+ format='[%(asctime)s] %(levelname)s: %(message)s',
11
  handlers=[logging.StreamHandler(sys.stdout)]
12
  )
13
  logger = logging.getLogger(__name__)
14
 
15
  def run_command(command, shell=True):
16
+ logger.info(f"πŸ‘‰ Running: {command}")
17
  try:
18
+ result = subprocess.run(
19
+ command,
20
+ shell=shell,
21
+ check=True,
22
+ stdout=sys.stdout,
23
+ stderr=sys.stderr
24
+ )
25
+ return result
26
  except subprocess.CalledProcessError as e:
27
  logger.error(f"❌ Command failed with exit code {e.returncode}")
28
+ time.sleep(1)
 
29
  sys.exit(e.returncode)
30
 
31
  def main():
32
+ logger.info("πŸš€ STARTUP SCRIPT INITIALIZED")
33
+ logger.info(f"πŸ“‚ CWD: {os.getcwd()}")
34
+ logger.info(f"🐍 Python: {sys.version}")
35
+ logger.info(f"πŸ“š PYTHONPATH: {sys.path}")
36
 
37
+ # 0. Debug Check: Can we trace the app?
38
+ logger.info("πŸ” Checking if 'app.main' is importable...")
39
+ try:
40
+ import app.main
41
+ logger.info("βœ… 'app.main' imported successfully!")
42
+ except ImportError as e:
43
+ logger.error(f"❌ Failed to import app.main: {e}")
44
+ # List files to see where we are
45
+ logger.info("πŸ“‚ File listing:")
46
+ for root, dirs, files in os.walk("."):
47
+ for name in files:
48
+ logger.info(os.path.join(root, name))
49
+ sys.exit(1)
50
+ except Exception as e:
51
+ logger.error(f"❌ Unexpected error importing app.main: {e}")
52
+ sys.exit(1)
53
+
54
  # 1. Run Migrations
55
  logger.info("πŸ› οΈ Running Database Migrations...")
 
56
  run_command("python -m alembic upgrade head")
57
+ logger.info("βœ… Migrations done.")
58
 
59
  # 2. Start Uvicorn
60
  host = "0.0.0.0"
61
  port = os.environ.get("PORT", "8000")
62
+ logger.info(f"πŸ”Œ Starting Server on {host}:{port}...")
63
 
 
64
  uvicorn_cmd = [
65
  "python", "-m", "uvicorn",
66
  "app.main:app",
67
  "--host", host,
68
  "--port", port,
69
+ "--log-level", "debug" # Force DEBUG level
70
  ]
71
 
72
+ logger.info(f"▢️ Executing: {' '.join(uvicorn_cmd)}")
 
 
73
  sys.stdout.flush()
 
74
 
75
+ # Use subprocess.run instead of exec to catch the exit
76
+ try:
77
+ proc = subprocess.run(uvicorn_cmd, check=False)
78
+ logger.info(f"πŸ›‘ Uvicorn exited with code: {proc.returncode}")
79
+ # If it exits cleanly (0), that's actually bad for a server (it should run forever)
80
+ if proc.returncode == 0:
81
+ logger.error("⚠️ Uvicorn exited with 0, but it should have kept running!")
82
+ except Exception as e:
83
+ logger.error(f"❌ Error running uvicorn: {e}")
84
+
85
+ logger.info("πŸ‘‹ Startup script finishing.")
86
 
87
  if __name__ == "__main__":
88
  main()