test_logging_system.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #!/usr/bin/env python3
  2. """
  3. Test script to demonstrate the logging system with rotation and cleanup
  4. """
  5. import os
  6. import sys
  7. import time
  8. from pathlib import Path
  9. # Add the src directory to the path
  10. project_root = Path(__file__).parent
  11. sys.path.insert(0, str(project_root / 'src'))
  12. def test_logging_system():
  13. """Test the logging system with rotation and cleanup."""
  14. print("🧪 Testing Advanced Logging System")
  15. print("=" * 60)
  16. # Set up test environment
  17. os.environ['LOG_TO_FILE'] = 'true'
  18. os.environ['LOG_FILE_PATH'] = 'test_logs/bot_test.log'
  19. os.environ['LOG_MAX_SIZE_MB'] = '1' # Small size for testing
  20. os.environ['LOG_BACKUP_COUNT'] = '3'
  21. os.environ['LOG_ROTATION_TYPE'] = 'size'
  22. os.environ['LOG_LEVEL'] = 'INFO'
  23. # Import after setting environment
  24. from logging_config import setup_logging, cleanup_logs, get_log_stats, format_log_stats
  25. print("📊 Test Configuration:")
  26. print(f" Log File: test_logs/bot_test.log")
  27. print(f" Max Size: 1 MB")
  28. print(f" Backup Count: 3")
  29. print(f" Rotation Type: size")
  30. print()
  31. # Initialize logging
  32. print("🔧 Initializing logging system...")
  33. logger = setup_logging()
  34. print("✅ Logging system initialized")
  35. print()
  36. # Generate lots of log entries to trigger rotation
  37. print("📝 Generating log entries to test rotation...")
  38. for i in range(1000):
  39. logger.info(f"Test log message {i:04d} - This is a sample trading bot log entry with some details about market data, orders, and trading activity.")
  40. if i % 100 == 0:
  41. print(f" Generated {i} log entries...")
  42. print("✅ Log generation complete")
  43. print()
  44. # Check log statistics
  45. print("📊 Log File Statistics:")
  46. stats = get_log_stats()
  47. for key, value in stats.items():
  48. if key == 'current_size_mb' or key == 'total_size_mb':
  49. print(f" {key}: {value:.2f} MB")
  50. else:
  51. print(f" {key}: {value}")
  52. print()
  53. # Show formatted stats
  54. print("📋 Formatted Log Status:")
  55. formatted_stats = format_log_stats()
  56. print(formatted_stats)
  57. print()
  58. # Test cleanup function
  59. print("🧹 Testing log cleanup (keeping files from last 1 day)...")
  60. cleanup_logs(days_to_keep=1)
  61. print("✅ Cleanup test complete")
  62. print()
  63. # Final statistics
  64. print("📊 Final Statistics:")
  65. final_stats = get_log_stats()
  66. print(format_log_stats(final_stats))
  67. print()
  68. # Show actual files created
  69. test_log_dir = Path('test_logs')
  70. if test_log_dir.exists():
  71. print("📁 Created Log Files:")
  72. for log_file in sorted(test_log_dir.glob('*.log*')):
  73. size_mb = log_file.stat().st_size / (1024 * 1024)
  74. print(f" 📄 {log_file.name} ({size_mb:.2f} MB)")
  75. print()
  76. print("🎉 Logging system test complete!")
  77. print()
  78. print("💡 Key Features Demonstrated:")
  79. print(" ✅ Automatic log rotation by file size")
  80. print(" ✅ Backup file management")
  81. print(" ✅ Log cleanup functionality")
  82. print(" ✅ Statistics and monitoring")
  83. print(" ✅ Configurable via environment variables")
  84. print()
  85. print("🚀 Ready for production use!")
  86. if __name__ == "__main__":
  87. test_logging_system()