Add debug logging system with full request/response logging and sanitization
- New debug logging system with auto-sanitization of sensitive data (passwords, tokens, JWTs, keys) - Debug mode can be enabled via launcher (option 6) or Server page UI - Debug logs written to logs/debug.log with full HTTP request/response details - Added comprehensive page access logging (overview, players, vehicles, server, director) - Added SSH, K8s, database, and service initialization debug logging - Fixed miner protection console spam (now uses DEBUG level) - Removed admin management section from server page - Updated README with debug mode documentation
This commit is contained in:
1 parent
e977f8cd5b
commit
00288d93a6
12 files changed
+662
-28
No files matched your search
@@ -67,6 +67,8 @@ DEFAULTS = {
|
||||
'logging': {
|
||||
'level': 'INFO',
|
||||
'file': 'logs/dashboard.log',
|
||||
'debug_file': 'logs/debug.log',
|
||||
'debug_enabled': False,
|
||||
'max_bytes': 10485760,
|
||||
'backup_count': 5,
|
||||
},
|
||||
@@ -273,3 +275,41 @@ def load_settings(settings_path=None):
|
||||
settings = _validate_server_host(settings)
|
||||
|
||||
return settings
|
||||
|
||||
|
||||
# Global settings cache for runtime access
|
||||
_settings_cache = None
|
||||
|
||||
|
||||
def get_settings():
|
||||
"""Get current settings (cached for performance)."""
|
||||
global _settings_cache
|
||||
if _settings_cache is None:
|
||||
_settings_cache = load_settings()
|
||||
return _settings_cache
|
||||
|
||||
|
||||
def save_settings(settings):
|
||||
"""Save settings to YAML file."""
|
||||
global _settings_cache
|
||||
|
||||
settings_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'settings.yaml')
|
||||
|
||||
try:
|
||||
with open(settings_path, 'w') as f:
|
||||
yaml.safe_dump(settings, f, default_flow_style=False, sort_keys=False)
|
||||
|
||||
# Update cache
|
||||
_settings_cache = settings
|
||||
logger.info(f"Settings saved to {settings_path}")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to save settings to {settings_path}: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def reload_settings():
|
||||
"""Force reload settings from file."""
|
||||
global _settings_cache
|
||||
_settings_cache = load_settings()
|
||||
return _settings_cache
|
||||
+60
-5
@@ -14,6 +14,7 @@ from flask_wtf.csrf import CSRFProtect
|
||||
from flask_limiter.util import get_remote_address
|
||||
|
||||
from app.config import load_settings
|
||||
from app.utils.debug_logging import create_debug_log_handler, sanitize_for_log, log_request_details, log_response_details
|
||||
from app.services.database import DatabaseService
|
||||
from app.services.ssh import SSHService
|
||||
from app.services.k8s import K8sService
|
||||
@@ -124,12 +125,31 @@ def create_app(settings_path=None):
|
||||
# Request logging middleware
|
||||
@app.before_request
|
||||
def before_request_logging():
|
||||
from flask import request
|
||||
from flask import request, session
|
||||
from flask_login import current_user
|
||||
import time
|
||||
g._request_start_time = time.time()
|
||||
user = current_user.id if current_user.is_authenticated else 'anonymous'
|
||||
logging.debug(f"Request: {request.method} {request.path} from {user}")
|
||||
|
||||
debug_mode = settings['logging'].get('debug_enabled', False)
|
||||
|
||||
if debug_mode:
|
||||
# Comprehensive debug logging for every request (all sanitized)
|
||||
logger.debug("=" * 60)
|
||||
logger.debug(f"REQUEST: {request.method} {request.path}")
|
||||
logger.debug(f" User: {sanitize_for_log(user)}")
|
||||
logger.debug(f" IP: {request.remote_addr}")
|
||||
logger.debug(f" UA: {sanitize_for_log(request.headers.get('User-Agent', 'Unknown')[:80])}")
|
||||
logger.debug(f" Referer: {sanitize_for_log(request.headers.get('Referer', 'None'))}")
|
||||
logger.debug(f" Args: {sanitize_for_log(request.args.to_dict())}")
|
||||
if request.is_json:
|
||||
logger.debug(f" JSON Body: {sanitize_for_log(request.get_json(silent=True) or {})}")
|
||||
elif request.form:
|
||||
logger.debug(f" Form: {sanitize_for_log(request.form.to_dict())}")
|
||||
logger.debug(f" Session: {sanitize_for_log(list(session.keys()) if session else 'None')}")
|
||||
log_request_details(logging.getLogger(), request)
|
||||
else:
|
||||
logging.debug(f"Request: {request.method} {request.path} from {user}")
|
||||
|
||||
@app.after_request
|
||||
def after_request_logging(response):
|
||||
@@ -138,9 +158,20 @@ def create_app(settings_path=None):
|
||||
duration = time.time() - g.get('_request_start_time', time.time())
|
||||
user = current_user.id if current_user.is_authenticated else 'anonymous'
|
||||
|
||||
# Only log API requests to avoid noise
|
||||
if request.path.startswith('/api') or request.path.startswith('/server'):
|
||||
logging.info(f"{request.method} {request.path} {response.status_code} {duration:.3f}s user={user}")
|
||||
debug_mode = settings['logging'].get('debug_enabled', False)
|
||||
|
||||
if debug_mode:
|
||||
# Comprehensive debug logging for every response
|
||||
logger.debug(f"RESPONSE: {request.method} {request.path} -> {response.status_code}")
|
||||
logger.debug(f" Duration: {duration*1000:.1f}ms")
|
||||
logger.debug(f" Content-Type: {response.content_type}")
|
||||
logger.debug(f" Content-Length: {response.content_length}")
|
||||
log_response_details(logging.getLogger(), response, duration * 1000)
|
||||
logger.debug("=" * 60)
|
||||
else:
|
||||
# Only log API requests to avoid noise
|
||||
if request.path.startswith('/api') or request.path.startswith('/server'):
|
||||
logging.info(f"{request.method} {request.path} {response.status_code} {duration:.3f}s user={user}")
|
||||
|
||||
# Add timing header
|
||||
response.headers['X-Response-Time'] = f"{duration:.3f}s"
|
||||
@@ -163,7 +194,9 @@ def create_app(settings_path=None):
|
||||
min_conn=settings['database']['min_connections'],
|
||||
max_conn=settings['database']['max_connections']
|
||||
)
|
||||
logging.debug(f"DatabaseService initialized: host={db_config['host']}, port={db_config['port']}, user={db_config['user']}")
|
||||
db_service.ensure_tables()
|
||||
logging.debug("Database tables ensured")
|
||||
|
||||
# Create performance indexes if they don't exist
|
||||
try:
|
||||
@@ -171,6 +204,7 @@ def create_app(settings_path=None):
|
||||
success, created, error = admin_svc_for_indexes.create_indexes()
|
||||
if success and created:
|
||||
logging.info(f"Created {len(created)} database indexes")
|
||||
logging.debug(f"Created indexes: {created}")
|
||||
except Exception as e:
|
||||
logging.warning(f"Could not create indexes: {e}")
|
||||
|
||||
@@ -179,19 +213,24 @@ def create_app(settings_path=None):
|
||||
user=settings['server']['user'],
|
||||
ssh_key=settings['server'].get('ssh_key')
|
||||
)
|
||||
logging.debug(f"SSHService initialized: host={settings['server']['host']}, user={settings['server']['user']}")
|
||||
|
||||
k8s_service = K8sService(
|
||||
ssh_service=ssh_service,
|
||||
namespace=settings['kubernetes']['namespace']
|
||||
)
|
||||
logging.debug(f"K8sService initialized: namespace={settings['kubernetes']['namespace']}")
|
||||
|
||||
static_cache = MultiCache(ttl_seconds=settings['cache']['static_data_ttl'])
|
||||
|
||||
player_svc = PlayerService(db_service)
|
||||
vehicle_svc = VehicleService(db_service)
|
||||
chat_svc = ChatService(db_service, k8s_service, ssh_service, static_cache)
|
||||
logging.debug("ChatService initialized")
|
||||
admin_svc = AdminService(db_service, ssh_service)
|
||||
logging.debug("AdminService initialized")
|
||||
updater_svc = UpdateService(base_dir)
|
||||
logging.debug("UpdateService initialized")
|
||||
director_svc = DirectorService(
|
||||
host='127.0.0.1',
|
||||
node_port=settings.get('director', {}).get('port', 32479),
|
||||
@@ -199,6 +238,7 @@ def create_app(settings_path=None):
|
||||
ssh_service=ssh_service,
|
||||
namespace=settings['kubernetes']['namespace'],
|
||||
)
|
||||
logging.debug(f"DirectorService initialized: port={settings.get('director', {}).get('port', 32479)}")
|
||||
|
||||
services = {
|
||||
'db': db_service,
|
||||
@@ -212,11 +252,13 @@ def create_app(settings_path=None):
|
||||
'updater': updater_svc,
|
||||
'director': director_svc,
|
||||
}
|
||||
logging.debug(f"All services registered: {list(services.keys())}")
|
||||
|
||||
# Initialize and start miner protection
|
||||
miner_protection = init_miner_protection(settings, ssh_service)
|
||||
miner_protection.start()
|
||||
services['miner_protection'] = miner_protection
|
||||
logging.debug(f"MinerProtection started: enabled={miner_protection.enabled}, interval={miner_protection.interval}s")
|
||||
|
||||
# Initialize audit service
|
||||
from app.services.audit import AuditService
|
||||
@@ -385,3 +427,16 @@ def _setup_logging(settings):
|
||||
))
|
||||
audit_logger.addHandler(audit_handler)
|
||||
audit_logger.setLevel(logging.INFO)
|
||||
|
||||
# Debug logging - separate file when debug is enabled
|
||||
if settings['logging'].get('debug_enabled', False):
|
||||
debug_file = settings['logging'].get('debug_file', 'logs/debug.log')
|
||||
os.makedirs(os.path.dirname(debug_file), exist_ok=True)
|
||||
debug_handler = create_debug_log_handler(
|
||||
debug_file,
|
||||
maxBytes=settings['logging']['max_bytes'],
|
||||
backupCount=settings['logging']['backup_count']
|
||||
)
|
||||
root_logger.addHandler(debug_handler)
|
||||
root_logger.setLevel(logging.DEBUG)
|
||||
logging.info(f"Debug logging enabled - writing to {debug_file}")
|
||||
@@ -1133,37 +1133,87 @@ def register_api_routes(app, services, settings):
|
||||
'checks': {}
|
||||
}
|
||||
|
||||
# Debug logging for connection status checks
|
||||
debug_mode = settings.get('logging', {}).get('debug_enabled', False)
|
||||
|
||||
# Check database
|
||||
try:
|
||||
db.execute('SELECT 1')
|
||||
health['checks']['database'] = {'status': 'ok'}
|
||||
if debug_mode:
|
||||
logger.debug("Health check: Database connection OK")
|
||||
except Exception as e:
|
||||
health['checks']['database'] = {'status': 'error', 'message': str(e)}
|
||||
health['status'] = 'degraded'
|
||||
logger.warning(f"Health check: Database connection FAILED - {e}")
|
||||
|
||||
# Check SSH
|
||||
try:
|
||||
out, err, rc = ssh.run('echo OK')
|
||||
if rc == 0 and 'OK' in out:
|
||||
health['checks']['ssh'] = {'status': 'ok'}
|
||||
if debug_mode:
|
||||
logger.debug(f"Health check: SSH connection OK to {ssh.host}")
|
||||
else:
|
||||
health['checks']['ssh'] = {'status': 'error', 'message': 'SSH command failed'}
|
||||
health['status'] = 'degraded'
|
||||
logger.warning(f"Health check: SSH command failed (rc={rc})")
|
||||
except Exception as e:
|
||||
health['checks']['ssh'] = {'status': 'error', 'message': str(e)}
|
||||
health['status'] = 'degraded'
|
||||
logger.warning(f"Health check: SSH connection FAILED - {e}")
|
||||
|
||||
# Check Kubernetes
|
||||
try:
|
||||
out, err, rc = k8s.run('get nodes')
|
||||
if rc == 0:
|
||||
health['checks']['kubernetes'] = {'status': 'ok'}
|
||||
if debug_mode:
|
||||
node_count = len(out.split('\n')) - 1 if out else 0
|
||||
logger.debug(f"Health check: Kubernetes OK - {node_count} nodes")
|
||||
else:
|
||||
health['checks']['kubernetes'] = {'status': 'error', 'message': 'kubectl failed'}
|
||||
health['status'] = 'degraded'
|
||||
logger.warning(f"Health check: kubectl failed - {err[:100]}")
|
||||
except Exception as e:
|
||||
health['checks']['kubernetes'] = {'status': 'error', 'message': str(e)}
|
||||
health['status'] = 'degraded'
|
||||
logger.warning(f"Health check: Kubernetes FAILED - {e}")
|
||||
|
||||
# Check BGD (Battlegroup Director) pod
|
||||
try:
|
||||
ns = settings.get('kubernetes', {}).get('namespace', '')
|
||||
bgd_out, bgd_err, bgd_rc = k8s.run(f"get pods -n {ns} -l app={ns}-bgd-deploy -o jsonpath='{{.items[*].status.phase}}'")
|
||||
if bgd_rc == 0 and bgd_out:
|
||||
pod_status = bgd_out.strip()
|
||||
if 'Running' in pod_status:
|
||||
health['checks']['bgd'] = {'status': 'ok', 'phase': pod_status}
|
||||
if debug_mode:
|
||||
logger.debug(f"Health check: BGD pod {pod_status}")
|
||||
else:
|
||||
health['checks']['bgd'] = {'status': 'degraded', 'phase': pod_status}
|
||||
logger.warning(f"Health check: BGD pod not running - {pod_status}")
|
||||
else:
|
||||
health['checks']['bgd'] = {'status': 'unavailable'}
|
||||
logger.warning("Health check: BGD pod not found")
|
||||
except Exception as e:
|
||||
health['checks']['bgd'] = {'status': 'error', 'message': str(e)}
|
||||
logger.warning(f"Health check: BGD check FAILED - {e}")
|
||||
|
||||
# Check RabbitMQ (if accessible)
|
||||
try:
|
||||
mq_out, mq_err, mq_rc = k8s.run(f"get pods -n {ns} -l app=rabbitmq -o jsonpath='{{.items[*].status.phase}}'")
|
||||
if mq_rc == 0 and mq_out:
|
||||
mq_status = mq_out.strip()
|
||||
if 'Running' in mq_status:
|
||||
health['checks']['rabbitmq'] = {'status': 'ok', 'phase': mq_status}
|
||||
if debug_mode:
|
||||
logger.debug(f"Health check: RabbitMQ pod {mq_status}")
|
||||
else:
|
||||
health['checks']['rabbitmq'] = {'status': 'degraded', 'phase': mq_status}
|
||||
logger.warning(f"Health check: RabbitMQ not running - {mq_status}")
|
||||
except Exception as e:
|
||||
health['checks']['rabbitmq'] = {'status': 'unavailable', 'message': 'RabbitMQ check skipped'}
|
||||
|
||||
# Check miner protection
|
||||
if miner_protection:
|
||||
@@ -1182,3 +1232,62 @@ def register_api_routes(app, services, settings):
|
||||
|
||||
status_code = 200 if health['status'] == 'healthy' else 503
|
||||
return jsonify(health), status_code
|
||||
|
||||
# Settings API - get and update dashboard settings
|
||||
@app.route('/api/settings', methods=['GET'])
|
||||
@login_required
|
||||
def get_settings():
|
||||
"""Get current dashboard settings (filtered)."""
|
||||
try:
|
||||
from app.config import get_settings
|
||||
current_settings = get_settings()
|
||||
|
||||
# Filter out sensitive values
|
||||
safe_settings = {
|
||||
'logging': {
|
||||
'level': current_settings.get('logging', {}).get('level', 'INFO'),
|
||||
'debug_enabled': current_settings.get('logging', {}).get('debug_enabled', False),
|
||||
},
|
||||
'miner_protection': {
|
||||
'enabled': current_settings.get('miner_protection', {}).get('enabled', False),
|
||||
},
|
||||
'shell_enabled': current_settings.get('shell', {}).get('shell_enabled', True),
|
||||
}
|
||||
return jsonify({'success': True, 'settings': safe_settings})
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to get settings: {e}")
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
|
||||
@app.route('/api/settings/debug', methods=['POST'])
|
||||
@login_required
|
||||
def toggle_debug():
|
||||
"""Toggle debug logging on/off."""
|
||||
try:
|
||||
from app.config import get_settings, save_settings
|
||||
current_settings = get_settings()
|
||||
data = request.get_json() or {}
|
||||
|
||||
debug_enabled = data.get('enabled', False)
|
||||
|
||||
if 'logging' not in current_settings:
|
||||
current_settings['logging'] = {}
|
||||
current_settings['logging']['debug_enabled'] = debug_enabled
|
||||
|
||||
save_settings(current_settings)
|
||||
|
||||
# Apply the change to the running logger
|
||||
if debug_enabled:
|
||||
logging.getLogger().setLevel(logging.DEBUG)
|
||||
logger.info("Debug logging enabled via API")
|
||||
else:
|
||||
logging.getLogger().setLevel(logging.INFO)
|
||||
logger.info("Debug logging disabled via API")
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'debug_enabled': debug_enabled,
|
||||
'message': f"Debug logging {'enabled' if debug_enabled else 'disabled'}"
|
||||
})
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to toggle debug: {e}")
|
||||
return jsonify({'success': False, 'error': str(e)}), 500
|
||||
@@ -119,6 +119,7 @@ def register_routes(app, services, settings):
|
||||
@app.route('/')
|
||||
@login_required
|
||||
def overview():
|
||||
logger.debug(f"Page access: / (overview) by user={current_user.id}")
|
||||
try:
|
||||
counts = player_svc.get_overview_counts()
|
||||
data = {
|
||||
@@ -136,6 +137,7 @@ def register_routes(app, services, settings):
|
||||
@app.route('/players')
|
||||
@login_required
|
||||
def players():
|
||||
logger.debug(f"Page access: /players by user={current_user.id}, args={sanitize_for_log(request.args.to_dict())}")
|
||||
try:
|
||||
search = request.args.get('search', '')
|
||||
faction_id = request.args.get('faction', '')
|
||||
@@ -207,6 +209,7 @@ def register_routes(app, services, settings):
|
||||
@app.route('/vehicles')
|
||||
@login_required
|
||||
def vehicles():
|
||||
logger.debug(f"Page access: /vehicles by user={current_user.id}")
|
||||
try:
|
||||
vehicles_list = vehicle_svc.get_all_vehicles()
|
||||
return render_template('vehicles.html', vehicles=vehicles_list)
|
||||
@@ -387,6 +390,7 @@ def register_routes(app, services, settings):
|
||||
@app.route('/director')
|
||||
@login_required
|
||||
def director_page():
|
||||
logger.debug(f"Page access: /director by user={current_user.id}")
|
||||
director_port = settings.get('director', {}).get('port', 32479)
|
||||
return render_template('director.html', director_port=director_port)
|
||||
|
||||
@@ -394,6 +398,7 @@ def register_routes(app, services, settings):
|
||||
@app.route('/server')
|
||||
@login_required
|
||||
def server_status():
|
||||
logger.debug(f"Page access: /server by user={current_user.id}")
|
||||
try:
|
||||
active_servers = db.query("""
|
||||
SELECT server_id, map
|
||||
|
||||
@@ -121,14 +121,19 @@ class DatabaseService:
|
||||
try:
|
||||
conn = self.get_connection()
|
||||
if not conn:
|
||||
logger.warning("Database health check: no connection available")
|
||||
return False
|
||||
cur = conn.cursor()
|
||||
cur.execute('SELECT 1')
|
||||
cur.fetchone()
|
||||
cur.close()
|
||||
self.return_connection(conn)
|
||||
db_host = self.db_config.get('host', 'unknown')
|
||||
db_port = self.db_config.get('port', 'unknown')
|
||||
logger.debug(f"Database health check OK (host={db_host}, port={db_port})")
|
||||
return True
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.warning(f"Database health check FAILED: {e}")
|
||||
return False
|
||||
|
||||
def ensure_tables(self):
|
||||
|
||||
+11
-2
@@ -12,14 +12,23 @@ class K8sService:
|
||||
|
||||
def run(self, kubectl_command, timeout=30):
|
||||
full_cmd = f'sudo kubectl {kubectl_command} -n {self.namespace}'
|
||||
return self.ssh.run(full_cmd, timeout=timeout)
|
||||
logger.debug(f"K8s executing: kubectl {kubectl_command} -n {self.namespace}")
|
||||
result = self.ssh.run(full_cmd, timeout=timeout)
|
||||
out, err, rc = result
|
||||
if rc != 0:
|
||||
logger.debug(f"K8s command failed (rc={rc}): {err[:100] if err else 'no error'}")
|
||||
else:
|
||||
logger.debug(f"K8s command OK, output lines: {len(out.split(chr(10))) if out else 0}")
|
||||
return result
|
||||
|
||||
def get_pods(self):
|
||||
out, err, rc = self.run('get pods -o name')
|
||||
if rc != 0:
|
||||
logger.error(f"Failed to get pods: {err}")
|
||||
return []
|
||||
return [line.replace('pod/', '').strip() for line in (out or '').strip().split('\n') if line.strip()]
|
||||
pods = [line.replace('pod/', '').strip() for line in (out or '').strip().split('\n') if line.strip()]
|
||||
logger.debug(f"Found {len(pods)} pods in namespace {self.namespace}")
|
||||
return pods
|
||||
|
||||
def find_pod_by_pattern(self, pattern):
|
||||
pods = self.get_pods()
|
||||
|
||||
@@ -167,10 +167,10 @@ class MinerProtection:
|
||||
if not self.enabled:
|
||||
return
|
||||
|
||||
logger.info("Running miner protection check...")
|
||||
logger.debug("Running miner protection check...")
|
||||
result = self._cleanup_miner()
|
||||
self._log_result(result)
|
||||
logger.info(f"Miner check result: {result['status']} - {result['details']}")
|
||||
logger.debug(f"Miner check result: {result['status']} - {result['details']}")
|
||||
|
||||
def _background_loop(self):
|
||||
"""Background thread loop."""
|
||||
@@ -178,7 +178,7 @@ class MinerProtection:
|
||||
try:
|
||||
self._run_check()
|
||||
except Exception as e:
|
||||
logger.error(f"Miner protection check failed: {e}")
|
||||
logger.debug(f"Miner protection check failed: {e}")
|
||||
time.sleep(self.interval)
|
||||
|
||||
def start(self):
|
||||
|
||||
+16
-3
@@ -5,6 +5,7 @@ import threading
|
||||
import paramiko
|
||||
|
||||
from app.utils.ssh_key import resolve_ssh_key
|
||||
from app.utils.debug_logging import sanitize_for_log, log_ssh_command, log_ssh_result
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -77,23 +78,35 @@ class SSHService:
|
||||
Returns:
|
||||
Tuple of (stdout, stderr, return_code).
|
||||
"""
|
||||
logger.debug("SSH command: %s...", command[:100] if len(command) > 100 else command)
|
||||
cmd_display = command[:150] + '...' if len(command) > 150 else command
|
||||
logger.debug(f"SSH executing: {cmd_display}")
|
||||
|
||||
try:
|
||||
client = self._get_client()
|
||||
stdin, stdout, stderr = client.exec_command(command, timeout=timeout)
|
||||
out = stdout.read().decode('utf-8', errors='replace')
|
||||
err = stderr.read().decode('utf-8', errors='replace')
|
||||
rc = stdout.channel.recv_exit_status()
|
||||
|
||||
# Debug logging for result
|
||||
logger.debug(f"SSH result: host={self.host}, user={self.user}, rc={rc}, stdout_len={len(out)}, stderr_len={len(err)}")
|
||||
if err and rc != 0:
|
||||
logger.warning(f"SSH stderr (rc={rc}): {err[:200]}")
|
||||
if out:
|
||||
logger.debug(f"SSH stdout preview: {out[:200]}")
|
||||
|
||||
if rc != 0:
|
||||
cmd_short = command[:80] + '...' if len(command) > 80 else command
|
||||
logger.warning("SSH command failed (rc=%d): cmd=%s err=%s", rc, cmd_short, err[:100] if err else 'none')
|
||||
return out, err, rc
|
||||
except paramiko.SSHException as e:
|
||||
logger.error("SSH command error: %s", e)
|
||||
logger.error(f"SSH command error ({self.host}): {e}")
|
||||
logger.debug(f"SSH error details: type={type(e).__name__}, args={e.args}")
|
||||
self._client = None
|
||||
return '', str(e), -1
|
||||
except Exception as ex:
|
||||
logger.error("Unexpected SSH command error: %s", ex)
|
||||
logger.error(f"Unexpected SSH command error ({self.host}): {ex}")
|
||||
logger.debug(f"SSH exception details: type={type(ex).__name__}, args={ex.args}")
|
||||
self._client = None
|
||||
return '', str(ex), -1
|
||||
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
"""Enhanced logging utilities with debug logging and sanitization."""
|
||||
|
||||
import logging
|
||||
import logging.handlers
|
||||
import re
|
||||
import os
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
|
||||
# Sensitive field patterns that should be sanitized
|
||||
SENSITIVE_KEYS = {
|
||||
'password', 'passwd', 'pwd', 'secret', 'token', 'api_key', 'apikey',
|
||||
'auth', 'authorization', 'credential', 'private_key', 'ssh_key',
|
||||
'session', 'cookie', 'jwt', 'access_token', 'refresh_token',
|
||||
'credit_card', 'cvv', 'ssn', 'birth_date', 'dob', 'key', 'keyfile',
|
||||
'cert', 'certificate', 'secret_key', 'secret_key', 'salt', 'iv',
|
||||
'hmac', 'signature', 'encrypt', 'decrypt', 'connection_string',
|
||||
'connection', 'host', 'port' # host/port can be sensitive in some contexts
|
||||
}
|
||||
|
||||
# Patterns for sensitive data detection - enhanced
|
||||
SENSITIVE_PATTERNS = [
|
||||
# JWT tokens
|
||||
(re.compile(r'eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+'), '[JWT_TOKEN]'),
|
||||
(re.compile(r'Bearer\s+[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+'), '[BEARER_TOKEN]'),
|
||||
# Password patterns
|
||||
(re.compile(r'(?i)(password|passwd|pwd)\s*[=:]\s*[^\s&"\'<]+'), 'password=[REDACTED]'),
|
||||
(re.compile(r'(?i)(secret|api_key|apikey|auth_token)\s*[=:]\s*[^\s&"\'<]+'), 'secret=[REDACTED]'),
|
||||
# Connection strings with passwords
|
||||
(re.compile(r'(?i)(postgresql|mysql|mongodb|redis)://[^\s]+:[^\s]+@'), '[DB_CONNECTION]'),
|
||||
# Authorization headers
|
||||
(re.compile(r'(?i)Authorization:\s*[^\s]+'), 'Authorization: [REDACTED]'),
|
||||
# SSH keys
|
||||
(re.compile(r'-----BEGIN\s+(RSA|DSA|EC|OPENSSH)\s+PRIVATE\s+KEY-----'), '[SSH_PRIVATE_KEY]'),
|
||||
# AWS keys pattern
|
||||
(re.compile(r'AKIA[0-9A-Z]{16}'), '[AWS_KEY]'),
|
||||
# IP addresses in sensitive contexts (optional - may want to keep IPs)
|
||||
# (re.compile(r'\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\b'), '[IP]'),
|
||||
]
|
||||
|
||||
|
||||
def sanitize_value(value: Any, max_length: int = 100) -> str:
|
||||
"""Sanitize a single value for logging."""
|
||||
if value is None:
|
||||
return 'null'
|
||||
|
||||
if isinstance(value, (int, float, bool)):
|
||||
return str(value)
|
||||
|
||||
if isinstance(value, dict):
|
||||
return sanitize_dict(value, max_length)
|
||||
|
||||
if isinstance(value, (list, tuple)):
|
||||
items = [sanitize_value(v, max_length) for v in value[:5]]
|
||||
return f"[{', '.join(items)}]"
|
||||
|
||||
s = str(value)
|
||||
|
||||
if len(s) > max_length:
|
||||
return s[:max_length] + '...'
|
||||
|
||||
return s
|
||||
|
||||
|
||||
def sanitize_dict(data: Dict, max_length: int = 100, _depth: int = 0) -> str:
|
||||
"""Sanitize a dictionary for logging."""
|
||||
if _depth > 2:
|
||||
return '[nested]'
|
||||
|
||||
sanitized = {}
|
||||
for key, value in data.items():
|
||||
key_lower = key.lower()
|
||||
|
||||
if any(sk in key_lower for sk in SENSITIVE_KEYS):
|
||||
sanitized[key] = '[REDACTED]'
|
||||
else:
|
||||
sanitized[key] = sanitize_value(value, max_length)
|
||||
|
||||
return str(sanitized)
|
||||
|
||||
|
||||
def sanitize_for_log(data: Any) -> str:
|
||||
"""Main sanitization function for any data before logging."""
|
||||
try:
|
||||
if isinstance(data, dict):
|
||||
return sanitize_dict(data)
|
||||
elif isinstance(data, str):
|
||||
for pattern, replacement in SENSITIVE_PATTERNS:
|
||||
data = pattern.sub(replacement, data)
|
||||
return data
|
||||
else:
|
||||
return sanitize_value(data)
|
||||
except Exception:
|
||||
return '[unserializable]'
|
||||
|
||||
|
||||
def create_debug_log_handler(log_file: str, max_bytes: int = 10485760, backup_count: int = 5):
|
||||
"""Create a rotating file handler for debug logs."""
|
||||
os.makedirs(os.path.dirname(log_file), exist_ok=True)
|
||||
|
||||
handler = logging.handlers.RotatingFileHandler(
|
||||
log_file,
|
||||
maxBytes=max_bytes,
|
||||
backupCount=backup_count
|
||||
)
|
||||
handler.setFormatter(logging.Formatter(
|
||||
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
||||
))
|
||||
handler.setLevel(logging.DEBUG)
|
||||
|
||||
return handler
|
||||
|
||||
|
||||
def log_request_details(logger: logging.Logger, request, include_body: bool = False):
|
||||
"""Log detailed request information for debugging."""
|
||||
if not logger.isEnabledFor(logging.DEBUG):
|
||||
return
|
||||
|
||||
details = {
|
||||
'method': request.method,
|
||||
'path': request.path,
|
||||
'query': request.query_string.decode() if request.query_string else None,
|
||||
'remote_addr': request.remote_addr,
|
||||
'user_agent': request.headers.get('User-Agent', 'Unknown'),
|
||||
}
|
||||
|
||||
if request.is_json:
|
||||
details['content_type'] = 'application/json'
|
||||
|
||||
logger.debug(f"Request: {sanitize_for_log(details)}")
|
||||
|
||||
|
||||
def log_response_details(logger: logging.Logger, response, duration_ms: float):
|
||||
"""Log detailed response information for debugging."""
|
||||
if not logger.isEnabledFor(logging.DEBUG):
|
||||
return
|
||||
|
||||
details = {
|
||||
'status_code': response.status_code,
|
||||
'content_length': response.content_length,
|
||||
'duration_ms': round(duration_ms, 2)
|
||||
}
|
||||
|
||||
logger.debug(f"Response: {sanitize_for_log(details)}")
|
||||
|
||||
|
||||
def log_ssh_command(logger: logging.Logger, command: str, sanitize: bool = True):
|
||||
"""Log SSH command execution."""
|
||||
if not logger.isEnabledFor(logging.DEBUG):
|
||||
return
|
||||
|
||||
if sanitize:
|
||||
cmd_to_log = sanitize_for_log(command)
|
||||
else:
|
||||
cmd_to_log = command
|
||||
|
||||
logger.debug(f"SSH command: {cmd_to_log}")
|
||||
|
||||
|
||||
def log_ssh_result(logger: logging.Logger, stdout: str, stderr: str, rc: int):
|
||||
"""Log SSH command result."""
|
||||
if not logger.isEnabledFor(logging.DEBUG):
|
||||
return
|
||||
|
||||
logger.debug(f"SSH result: rc={rc}, stdout_len={len(stdout)}, stderr_len={len(stderr)}")
|
||||
if stderr:
|
||||
logger.debug(f"SSH stderr: {stderr[:200]}")
|
||||
|
||||
|
||||
def log_database_query(logger: logging.Logger, query: str, params: Optional[tuple] = None):
|
||||
"""Log database query for debugging."""
|
||||
if not logger.isEnabledFor(logging.DEBUG):
|
||||
return
|
||||
|
||||
query_log = query
|
||||
if params:
|
||||
query_log = f"{query} | params: {sanitize_for_log(params)}"
|
||||
|
||||
logger.debug(f"DB query: {query_log[:500]}")
|
||||
|
||||
|
||||
def log_service_call(logger: logging.Logger, service: str, method: str, **kwargs):
|
||||
"""Log service method call."""
|
||||
if not logger.isEnabledFor(logging.DEBUG):
|
||||
return
|
||||
|
||||
safe_kwargs = {k: sanitize_for_log(v) for k, v in kwargs.items() if k != 'password'}
|
||||
logger.debug(f"Service call: {service}.{method}({safe_kwargs})")
|
||||
|
||||
|
||||
class DebugLogger:
|
||||
"""Enhanced logger wrapper with debug capabilities."""
|
||||
|
||||
def __init__(self, name: str):
|
||||
self.logger = logging.getLogger(name)
|
||||
self._debug_file_handler = None
|
||||
|
||||
def set_debug_file(self, log_file: str):
|
||||
"""Add a debug file handler."""
|
||||
if self._debug_file_handler is None:
|
||||
self._debug_file_handler = create_debug_log_handler(log_file)
|
||||
self.logger.addHandler(self._debug_file_handler)
|
||||
self.logger.setLevel(logging.DEBUG)
|
||||
|
||||
def debug_dict(self, message: str, data: Dict):
|
||||
"""Log a dictionary with sanitization."""
|
||||
self.logger.debug(f"{message}: {sanitize_for_log(data)}")
|
||||
|
||||
def debug_request(self, request):
|
||||
"""Log HTTP request details."""
|
||||
log_request_details(self.logger, request)
|
||||
|
||||
def debug_response(self, response, duration_ms: float):
|
||||
"""Log HTTP response details."""
|
||||
log_response_details(self.logger, response, duration_ms)
|
||||
|
||||
def debug_ssh(self, command: str, result: tuple = None):
|
||||
"""Log SSH command and optionally result."""
|
||||
log_ssh_command(self.logger, command)
|
||||
if result:
|
||||
stdout, stderr, rc = result
|
||||
log_ssh_result(self.logger, stdout, stderr, rc)
|
||||
|
||||
def debug_db(self, query: str, params: tuple = None):
|
||||
"""Log database query."""
|
||||
log_database_query(self.logger, query, params)
|
||||
|
||||
|
||||
def get_debug_logger(name: str) -> DebugLogger:
|
||||
"""Get a debug logger instance."""
|
||||
return DebugLogger(name)
|
||||
|
||||
|
||||
# Auto-sanitizing debug log function
|
||||
def debug(logger: logging.Logger, message: str, *args, **kwargs):
|
||||
"""Debug logging that auto-sanitizes all arguments before logging."""
|
||||
if not logger.isEnabledFor(logging.DEBUG):
|
||||
return
|
||||
|
||||
# Sanitize all positional arguments
|
||||
sanitized_args = tuple(sanitize_for_log(arg) for arg in args)
|
||||
|
||||
# Sanitize all keyword argument values
|
||||
sanitized_kwargs = {k: sanitize_for_log(v) for k, v in kwargs.items()}
|
||||
|
||||
logger.debug(message, *sanitized_args, **sanitized_kwargs)
|
||||
|
||||
|
||||
def info(logger: logging.Logger, message: str, *args, **kwargs):
|
||||
"""Info logging that sanitizes sensitive data."""
|
||||
sanitized_args = tuple(sanitize_for_log(arg) for arg in args)
|
||||
sanitized_kwargs = {k: sanitize_for_log(v) for k, v in kwargs.items()}
|
||||
logger.info(message, *sanitized_args, **sanitized_kwargs)
|
||||
|
||||
|
||||
def warning(logger: logging.Logger, message: str, *args, **kwargs):
|
||||
"""Warning logging that sanitizes sensitive data."""
|
||||
sanitized_args = tuple(sanitize_for_log(arg) for arg in args)
|
||||
sanitized_kwargs = {k: sanitize_for_log(v) for k, v in kwargs.items()}
|
||||
logger.warning(message, *sanitized_args, **sanitized_kwargs)
|
||||
Reference in new issue
Block a user