test_logging_manual.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. """
  2. Manual test script for logging configuration.
  3. This script demonstrates the logging system functionality and can be run
  4. to verify that logging is working correctly.
  5. """
  6. import sys
  7. import tempfile
  8. from pathlib import Path
  9. # Add src to path
  10. sys.path.insert(0, str(Path(__file__).parent / "src"))
  11. from config.logging import (
  12. configure_logging,
  13. configure_development_logging,
  14. configure_production_logging,
  15. get_logger,
  16. )
  17. def test_console_logging():
  18. """Test console logging with JSON format."""
  19. print("\n=== Testing Console Logging (JSON Format) ===")
  20. configure_logging(
  21. log_level="INFO",
  22. log_to_console=True,
  23. log_to_file=False,
  24. json_format=True,
  25. )
  26. logger = get_logger(__name__)
  27. logger.info("test_message", test_key="test_value", user_id="user_123")
  28. logger.warning("warning_message", warning_type="test")
  29. logger.error("error_message", error_code=500)
  30. print("✓ Console logging test completed\n")
  31. def test_file_logging():
  32. """Test file logging with rotation."""
  33. print("=== Testing File Logging ===")
  34. # Create temporary log file
  35. with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.log') as f:
  36. log_file = f.name
  37. try:
  38. configure_logging(
  39. log_level="DEBUG",
  40. log_file=log_file,
  41. log_to_console=False,
  42. log_to_file=True,
  43. json_format=True,
  44. max_file_size=1024, # Small size for testing
  45. backup_count=2,
  46. )
  47. logger = get_logger(__name__)
  48. logger.debug("debug_message", detail="This is a debug message")
  49. logger.info("info_message", detail="This is an info message")
  50. logger.warning("warning_message", detail="This is a warning")
  51. logger.error("error_message", detail="This is an error")
  52. # Read and display log file content
  53. log_path = Path(log_file)
  54. if log_path.exists():
  55. content = log_path.read_text()
  56. print(f"Log file created at: {log_file}")
  57. print(f"Log file size: {log_path.stat().st_size} bytes")
  58. print(f"Log entries: {len(content.splitlines())}")
  59. print("✓ File logging test completed\n")
  60. else:
  61. print("✗ Log file was not created\n")
  62. finally:
  63. # Cleanup - close all handlers first
  64. import logging
  65. for handler in logging.root.handlers[:]:
  66. handler.close()
  67. logging.root.removeHandler(handler)
  68. # Now try to delete the file
  69. try:
  70. if Path(log_file).exists():
  71. Path(log_file).unlink()
  72. except PermissionError:
  73. # File is still locked on Windows, that's okay
  74. print(f"Note: Could not delete temp log file (file locked): {log_file}")
  75. def test_development_logging():
  76. """Test development logging configuration."""
  77. print("=== Testing Development Logging (Human-Readable) ===")
  78. configure_development_logging()
  79. logger = get_logger(__name__)
  80. logger.debug("development_debug", feature="new_feature", status="testing")
  81. logger.info("development_info", action="user_login", user="dev_user")
  82. print("✓ Development logging test completed\n")
  83. def test_context_binding():
  84. """Test logger context binding."""
  85. print("=== Testing Context Binding ===")
  86. configure_logging(
  87. log_level="INFO",
  88. log_to_console=True,
  89. json_format=True,
  90. )
  91. # Create logger with bound context
  92. logger = get_logger(__name__)
  93. request_logger = logger.bind(request_id="req_12345", user_id="user_789")
  94. request_logger.info("request_started", method="GET", path="/api/documents")
  95. request_logger.info("request_processing", step="validation")
  96. request_logger.info("request_completed", status_code=200, duration_ms=45)
  97. print("✓ Context binding test completed\n")
  98. def test_exception_logging():
  99. """Test exception logging with stack traces."""
  100. print("=== Testing Exception Logging ===")
  101. configure_logging(
  102. log_level="ERROR",
  103. log_to_console=True,
  104. json_format=True,
  105. )
  106. logger = get_logger(__name__)
  107. try:
  108. # Simulate an error
  109. result = 1 / 0
  110. except ZeroDivisionError as e:
  111. logger.error(
  112. "division_error",
  113. error=str(e),
  114. operation="divide",
  115. exc_info=True,
  116. )
  117. print("✓ Exception logging test completed\n")
  118. def test_log_levels():
  119. """Test different log levels."""
  120. print("=== Testing Log Levels ===")
  121. configure_logging(
  122. log_level="DEBUG",
  123. log_to_console=True,
  124. json_format=False, # Human-readable for this test
  125. )
  126. logger = get_logger(__name__)
  127. logger.debug("This is a DEBUG message")
  128. logger.info("This is an INFO message")
  129. logger.warning("This is a WARNING message")
  130. logger.error("This is an ERROR message")
  131. logger.critical("This is a CRITICAL message")
  132. print("✓ Log levels test completed\n")
  133. if __name__ == "__main__":
  134. print("=" * 60)
  135. print("Logging System Manual Tests")
  136. print("=" * 60)
  137. try:
  138. test_console_logging()
  139. test_file_logging()
  140. test_development_logging()
  141. test_context_binding()
  142. test_exception_logging()
  143. test_log_levels()
  144. print("=" * 60)
  145. print("All tests completed successfully! ✓")
  146. print("=" * 60)
  147. except Exception as e:
  148. print(f"\n✗ Test failed with error: {e}")
  149. import traceback
  150. traceback.print_exc()
  151. sys.exit(1)