fix(starlark): logging improvements and code quality fixes

Logging improvements (pages_v3.py):
- Add logging import and create module logger
- Replace print() calls with logger.warning() with "[Pages V3]" prefix
- Use logger.exception() for outer try/catch with exc_info=True
- Narrow exception handling to OSError, json.JSONDecodeError for file operations

API improvements (api_v3.py):
- Remove unnecessary f-strings (Ruff F541) from ImportError messages
- Narrow upload exception handling to ValueError, OSError, IOError
- Use logger.exception() with context for better debugging
- Remove early return in get_starlark_status() to allow standalone mode fallback
- Sanitize error messages returned to client (don't expose internal details)

Benefits:
- Better log context with consistent prefixes
- More specific exception handling prevents masking unexpected errors
- Standalone/web-service-only mode now works for status endpoint
- Stack traces preserved for debugging without exposing to clients

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
Chuck
2026-02-19 21:44:39 -05:00
parent 92fb0989ce
commit 5bb9a59162
2 changed files with 13 additions and 14 deletions

View File

@@ -7000,7 +7000,7 @@ def _get_tronbyte_repository_class() -> Type[Any]:
module = importlib.util.module_from_spec(spec)
if module is None:
raise ImportError(f"Failed to create module from spec for tronbyte_repository")
raise ImportError("Failed to create module from spec for tronbyte_repository")
sys.modules["tronbyte_repository"] = module
spec.loader.exec_module(module)
@@ -7027,7 +7027,7 @@ def _get_pixlet_renderer_class() -> Type[Any]:
module = importlib.util.module_from_spec(spec)
if module is None:
raise ImportError(f"Failed to create module from spec for pixlet_renderer")
raise ImportError("Failed to create module from spec for pixlet_renderer")
sys.modules["pixlet_renderer"] = module
spec.loader.exec_module(module)
@@ -7212,9 +7212,6 @@ def _install_star_file(app_id: str, star_file_path: str, metadata: Dict[str, Any
def get_starlark_status():
"""Get Starlark plugin status and Pixlet availability."""
try:
if not api_v3.plugin_manager:
return jsonify({'status': 'error', 'message': 'Plugin manager not initialized', 'pixlet_available': False}), 500
starlark_plugin = _get_starlark_plugin()
if starlark_plugin:
info = starlark_plugin.get_info()
@@ -7445,9 +7442,9 @@ def upload_starlark_app():
except OSError:
pass
except Exception as e:
logger.error(f"Error uploading starlark app: {e}")
return jsonify({'status': 'error', 'message': str(e)}), 500
except (ValueError, OSError, IOError) as e:
logger.exception("[Starlark] Error uploading starlark app")
return jsonify({'status': 'error', 'message': 'Failed to upload app'}), 500
@api_v3.route('/starlark/apps/<app_id>', methods=['DELETE'])

View File

@@ -1,7 +1,10 @@
from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
import json
import logging
from pathlib import Path
logger = logging.getLogger(__name__)
# Will be initialized when blueprint is registered
config_manager = None
plugin_manager = None
@@ -477,8 +480,8 @@ def _load_starlark_config_partial(app_id):
try:
with open(schema_file, 'r') as f:
schema = json.load(f)
except Exception as e:
print(f"Warning: Could not load schema for {app_id}: {e}")
except (OSError, json.JSONDecodeError) as e:
logger.warning(f"[Pages V3] Could not load schema for {app_id}: {e}", exc_info=True)
# Load config from config.json if it exists
config = {}
@@ -487,8 +490,8 @@ def _load_starlark_config_partial(app_id):
try:
with open(config_file, 'r') as f:
config = json.load(f)
except Exception as e:
print(f"Warning: Could not load config for {app_id}: {e}")
except (OSError, json.JSONDecodeError) as e:
logger.warning(f"[Pages V3] Could not load config for {app_id}: {e}", exc_info=True)
return render_template(
'v3/partials/starlark_config.html',
@@ -505,6 +508,5 @@ def _load_starlark_config_partial(app_id):
)
except Exception as e:
import traceback
traceback.print_exc()
logger.exception(f"[Pages V3] Error loading starlark config for {app_id}")
return f'<div class="text-red-500 p-4">Error loading starlark config: {str(e)}</div>', 500