import os
import sys
import traceback
import json
import threading
from datetime import datetime
class SolanaLogger:
"""
Comprehensive logging utility with debug toggling and advanced error tracking.
"""
_instance = None
_lock = threading.Lock()
code
Assistant
Yes, I see the code you posted. It defines a comprehensive logging utility called SolanaLogger, which implements a singleton design pattern to ensure that only one logging instance is created throughout the application. Here's a brief overview of its main features and functionalities:
Singleton Pattern: Ensures a single instance of the SolanaLogger class is used across the application.
Logging Configuration: Loads logging configuration from a JSON file (logging_config.json) which includes settings like debug mode, maximum log size, and a cleaning threshold for log files.
User
Assistant
def __new__(cls, name=None):
"""Singleton pattern to ensure a single logging instance."""
if not cls._instance:
with cls._lock:
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self, name=None):
"""Initialize logging configuration."""
if not hasattr(self, '_initialized'):
# Base configuration
self.base_log_dir = r'C:\solana_rust_bot\logs'
self.debug_enabled = False
self.module_name = name if name else 'unknown'
# Load logging configuration
self.config_path = os.path.join(self.base_log_dir, 'logging_config.json')
self._load_config()
self._ensure_log_directories()
self._initialized = True
def _ensure_log_directories(self):
"""Create log directories if they don't exist."""
log_dirs = [
os.path.join(self.base_log_dir, subdir)
for subdir in ['debug', 'errors', 'info', 'system', 'trading', 'archived']
]
for dir_path in log_dirs:
os.makedirs(dir_path, exist_ok=True)
def _load_config(self):
"""Load logging configuration from a JSON file."""
try:
if os.path.exists(self.config_path):
with open(self.config_path, 'r') as config_file:
config = json.load(config_file)
self.debug_enabled = config.get('debug_mode', False)
self.max_log_size = config.get('max_log_size', 204800) # 200 KB
self.clean_threshold = config.get('clean_threshold', 102400) # 100 KB
else:
self._save_config()
except Exception as e:
print(f"Error loading logging config: {e}")
self.debug_enabled = False
def _save_config(self):
"""Save logging configuration to a JSON file."""
try:
with open(self.config_path, 'w') as config_file:
json.dump({'debug_mode': self.debug_enabled,
'max_log_size': self.max_log_size,
'clean_threshold': self.clean_threshold}, config_file)
except Exception as e:
print(f"Error saving logging config: {e}")
def _check_log_size(self, log_type='system'):
"""Check log file size and refresh it if it exceeds the threshold."""
log_file_path = os.path.join(self.base_log_dir, log_type, f"{log_type}.log")
if os.path.exists(log_file_path):
current_size = os.path.getsize(log_file_path)
if current_size >= self.clean_threshold:
# Clear the log file to begin anew
with open(log_file_path, 'w'):
pass # Just open and close to clear the file
def _write_log(self, message, log_type='system', caller_name=None, is_debug=False, extra=None):
"""Write log message with comprehensive error tracking."""
if is_debug and not self.debug_enabled:
return
if caller_name is None:
caller_name = self.module_name
if log_type not in ['debug', 'errors', 'info', 'system', 'trading', 'critical']:
log_type = 'system'
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
# Format the log entry with optional extra parameters
extra_str = self._format_extra(extra)
log_entry = f"{timestamp} | {log_type.upper()} | {caller_name}: {message}{extra_str}\n"
# Use 'errors' directory for critical logs
if log_type == 'critical':
log_type = 'errors'
# Check log size before writing
self._check_log_size(log_type)
log_file_path = os.path.join(self.base_log_dir, log_type, f"{log_type}.log")
try:
with open(log_file_path, 'a') as log_file:
log_file.write(log_entry)
except Exception as e:
print(f"Logging error: {e}", file=sys.stderr)
def _format_extra(self, extra):
"""Format extra parameters for logging."""
if not extra:
return ""
try:
return f" | {json.dumps(extra)}"
except:
return f" | {str(extra)}"
def debug(self, message, caller_name=None, extra=None):
"""Log debug messages with contextual information."""
self._write_log(message, 'debug', caller_name, is_debug=True, extra=extra)
def info(self, message, log_type='info', caller_name=None, extra=None):
"""Log informational messages with contextual information."""
self._write_log(message, log_type, caller_name, extra=extra)
def error(self, message, log_type='errors', caller_name=None, include_traceback=True, extra=None):
"""Log error messages with detailed context and traceback."""
full_message = message
if include_traceback:
trace = traceback.format_exc()
full_message += f"\n--- TRACEBACK ---\n{trace}"
self._write_log(full_message, log_type, caller_name, extra=extra)
def critical(self, message, caller_name=None, extra=None):
"""Log critical error messages with a traceback."""
full_message = message
trace = traceback.format_exc()
full_message += f"\n--- TRACEBACK ---\n{trace}"
self._write_log(full_message, 'critical', caller_name, extra=extra)
def exception(self, message, caller_name=None, extra=None):
"""Log exception messages with a traceback."""
full_message = message
trace = traceback.format_exc()
full_message += f"\n--- TRACEBACK ---\n{trace}"
self._write_log(full_message, 'errors', caller_name, extra=extra)
def toggle_debug(enable=None):
logger = SolanaLogger()
return logger.toggle_debug(enable) DO YOU SEE THIS ?
Log Directory Management: Automatically creates log directories for different log types (debug, errors, info, system, trading, archived) if they do not exist.
Log Size Management: Checks the size of log files and clears them if they exceed a predefined threshold.
Log Writing: Provides methods to write logs of various types: debug, info, error, critical, and exception. It also includes options to log extra contextual information and handle potential exceptions during logging.
Error Tracking: Includes detailed error tracking by capturing stack traces when logging errors and exceptions.
Convenience Functions: Provides utility functions (log_debug, log_info, log_error, log_critical, log_exception) for easier logging without needing to manage logger instances explicitly each time.
Debug Mode Toggle: Allows toggling of debug mode to control whether debug messages are logged.
This logger seems to be structured to facilitate easier debugging and logging in a Solana-related Rust bot application, as indicated by its naming and file paths. If you have specific questions about the implementation or need help with something related to it, feel free to ask!
import asyncio
import torch
import time
import json
import base58
import os
import numpy as np
from typing import Optional, Dict, List, Set
from dataclasses import dataclass, field
from collections import deque
from concurrent.futures import ThreadPoolExecutor
from decimal import Decimal
from dotenv import load_dotenv
from solana_rust_bot import TradingCore
from solana_logger import SolanaLogger
Load environment variables
load_dotenv()
Initialize SolanaLogger
logger = SolanaLogger(name)
@dataclass
class ParserMetrics:
processed_count: int = 0
success_count: int = 0
error_count: int = 0
avg_process_time: float = 0.0
sandwich_opportunities: int = 0
impact_opportunities: int = 0
last_gc_time: float = 0.0
peak_memory: float = 0.0
profitable_ops: int = 0
missed_ops: int = 0
latency_stats: List[float] = field(default_factory=list)
last_update: float = field(default_factory=time.time)
execution_times: deque = field(default_factory=lambda: deque(maxlen=1000))
def __post_init__(self):
try:
# Validate numeric fields
if not all(isinstance(x, (int, float)) for x in
[self.amount_in, self.amount_out, self.profit_pct,
self.impact, self.confidence]):
logger.error("Invalid numeric values in opportunity",
extra={"values": {
"amount_in": self.amount_in,
"amount_out": self.amount_out,
"profit_pct": self.profit_pct
}})
raise ValueError("Invalid numeric values in opportunity")
# Validate timestamp
if self.timestamp > time.time() + 1:
logger.error("Future timestamp detected",
extra={"timestamp": self.timestamp})
raise ValueError("Future timestamp detected")
# Validate type
if self.type not in ['sandwich', 'impact']:
logger.error("Invalid opportunity type",
extra={"type": self.type})
raise ValueError(f"Invalid opportunity type: {self.type}")
except Exception as e:
logger.exception("Error in OpportunityInfo validation",
extra={"error": str(e)})
raise
class EnhancedParser:
def init(self):
"""Initialize parser with enhanced CUDA optimizations"""
logger.info("Initializing EnhancedParser")
self.recent_transactions = deque(maxlen=1000)
self.opportunity_history = deque(maxlen=1000)
self.metrics = ParserMetrics()
code
Certainly! To improve the logging in the provided code, we can follow a few principles:
Contextual Information: Include more context in the log messages to help diagnose any issues effectively. This can include variable values, method names, and key decision points in the logic.
Different Log Levels: Ensure that each log message uses the appropriate log level (e.g., debug, info, warning, error, critical).
Structured Logs: Use structured logging where possible, so logs can be parsed easily, which is helpful for monitoring or analyzing logs using tools.
Detailed Exception Logging: When catching exceptions, include relevant context to understand what went wrong.
Performance Metrics: Whenever performance metrics are logged, include the context to understand their significance.
Here is a modified version of your code with enhanced logging:
python
# (Imports and initial setup remain unchanged)
class EnhancedParser:
def __init__(self):
logger.info("Initializing EnhancedParser")
self.recent_transactions = deque(maxlen=1000)
self.opportunity_history = deque(maxlen=1000)
self.metrics = ParserMetrics()
if not os.getenv('RPC_URL'):
logger.error("RPC_URL environment variable is missing")
raise ValueError("RPC_URL environment variable is required")
try:
private_key = os.getenv('SOLANA_PRIVATE_KEY')
if not private_key:
logger.error("SOLANA_PRIVATE_KEY environment variable is missing")
raise ValueError("SOLANA_PRIVATE_KEY environment variable is required")
key_bytes = base58.b58decode(private_key)
self.trading_core = TradingCore(key_bytes)
self._initialize_gpu()
self.recent_txs = deque(maxlen=1000)
self.victim_txs = {}
self.impact_txs = {}
self.sandwich_windows = {}
self.thread_pool = ThreadPoolExecutor(max_workers=2)
self.pattern_cache = deque(maxlen=1000)
self.pool_states: Dict[str, Dict] = {}
self._load_thresholds()
self._setup_buffers()
logger.info("EnhancedParser initialization completed successfully")
except Exception as e:
logger.error("Failed to initialize EnhancedParser", extra={"error": str(e)})
raise
async def analyze_transaction(self, tx_data: bytes) -> Optional[OpportunityInfo]:
start_time = time.perf_counter()
logger.debug("Starting transaction analysis for data: %s", tx_data.hex())
try:
with torch.cuda.stream(self.streams['analyze']):
data_tensor = await self._prepare_data(tx_data)
if data_tensor is None:
logger.debug("Invalid transaction data, skipping analysis")
return None
logger.debug("Processing transaction in parallel streams")
sandwich_future = self._check_sandwich_opportunity(data_tensor.clone(), tx_data)
impact_future = self._check_impact_opportunity(data_tensor.clone(), tx_data)
sandwich_result, impact_result = await asyncio.gather(sandwich_future, impact_future)
opportunity = self._select_best_opportunity(sandwich_result, impact_result)
latency = time.perf_counter() - start_time
if opportunity:
self.metrics.success_count += 1
self.metrics.latency_stats.append(latency)
if latency <= self.MAX_LATENCY:
self.metrics.profitable_ops += 1
logger.info("Profitable opportunity found", extra={"type": opportunity.type, "profit": opportunity.profit_pct, "latency": latency})
else:
self.metrics.missed_ops += 1
logger.warning("Opportunity missed due to high latency", extra={"latency": latency, "max_latency": self.MAX_LATENCY})
self._update_patterns(opportunity)
return opportunity
except Exception as e:
self.metrics.error_count += 1
logger.exception("Transaction analysis failed for tx_data: %s", tx_data.hex(), extra={"error": str(e)})
return None
finally:
self.metrics.processed_count += 1
process_time = time.perf_counter() - start_time
self._update_metrics(process_time)
logger.debug("Transaction analysis processed in %.2f seconds", process_time)
async def _check_sandwich_opportunity(self, tx_tensor: torch.Tensor, raw_data: bytes) -> Optional[OpportunityInfo]:
try:
with torch.cuda.stream(self.streams['sandwich']):
with torch.autocast(device_type='cuda', dtype=torch.float16):
amount_in = float(tx_tensor[0])
amount_out = float(tx_tensor[1])
pool = tx_tensor[2:34].cpu().numpy().tobytes().hex()
logger.debug("Analyzing sandwich opportunity with amount_in: %.2f, amount_out: %.2f, pool: %s",
amount_in, amount_out, pool)
if not (self.SANDWICH_CONFIG['min_victim_size'] <= amount_in <= self.SANDWICH_CONFIG['max_victim_size']):
logger.debug("Transaction size outside sandwich parameters: amount_in=%.2f", amount_in)
return None
front_run = amount_in * self.SANDWICH_CONFIG['front_run_multiplier']
back_run = front_run * self.SANDWICH_CONFIG['back_run_multiplier']
impact = await self._calculate_price_impact(amount_in, amount_out, pool)
if impact > self.SANDWICH_CONFIG['max_impact']:
logger.debug("Impact too high for sandwich: %.5f", impact)
return None
profit = await self._calculate_sandwich_profit(front_run, back_run, impact, pool)
if profit < self.SANDWICH_CONFIG['min_profit']:
logger.debug("Insufficient profit for sandwich: %.5f", profit)
return None
pool_state = await self._get_pool_state(pool)
logger.info("Valid sandwich opportunity found", extra={"profit": profit, "impact": impact, "front_run": front_run, "back_run": back_run})
return OpportunityInfo(
raw_data=raw_data,
pool_address=pool,
amount_in=front_run,
amount_out=back_run,
profit_pct=profit,
impact=impact,
confidence=self.PATTERN_CONFIDENCE,
timestamp=time.time(),
type='sandwich',
priority=1,
pool_state=pool_state,
metadata={
'victim_size': amount_in,
'front_run_size': front_run,
'back_run_size': back_run,
'estimated_profit': profit
}
)
except Exception as e:
logger.exception("Sandwich opportunity check failed for raw_data: %s", raw_data.hex(), extra={"error": str(e)})
return None
async def cleanup(self):
logger.info("Starting cleanup process")
try:
if torch.cuda.is_available():
logger.debug("Cleaning up GPU resources")
torch.cuda.synchronize()
for stream in self.streams.values():
stream.synchronize()
logger.debug("Releasing GPU buffers")
self.process_buffer = None
self.pattern_buffer = None
self.state_buffer = None
torch.cuda.empty_cache()
logger.debug("Clearing data structures")
self.pool_states.clear()
self.pattern_cache.clear()
self.recent_transactions.clear()
self.opportunity_history.clear()
logger.debug("Shutting down thread pool")
self.thread_pool.shutdown(wait=True)
logger.info("Cleanup completed successfully")
except Exception as e:
logger.exception("Cleanup process failed", extra={"error": str(e)})
raise
def _monitor_performance(self):
try:
metrics = {
'gpu_utilization': torch.cuda.utilization(),
'memory_allocated': torch.cuda.memory_allocated() / 1024**2,
'memory_reserved': torch.cuda.memory_reserved() / 1024**2,
'avg_latency': np.mean(self.metrics.latency_stats[-100:]) * 1000 if self.metrics.latency_stats else 0,
'success_rate': self.metrics.success_count / max(self.metrics.processed_count, 1)
}
logger.info("Performance metrics", extra={"metrics": metrics})
return metrics
except Exception as e:
logger.exception("Performance monitoring failed", extra={"error": str(e)})
return None
# The remainder of your code would stay the same...
Summary of Changes:
Detailed Method Entry/Exit Logs: Each method now logs when it starts and completes execution, along with key parameter values.
Error Context: The error logging has been updated to include the specific context of the operation that failed.
Metrics Logging: Performance logs have been enhanced with more details on GPU utilization and memory usage.
Warnings for Conditions: Added logging to indicate when certain conditions are not met, such as outside thresholds (with debug logs).
Consistency and Formatting: Improved format strings for better readability in logs, and ensured consistent formatting throughout.
This enhanced logging will help in tracing the execution flow and understanding the context during debugging, especially when dealing with complex asynchronous operations and GPU computations.