logging_config.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. """
  2. Logging configuration for the application.
  3. """
  4. import logging
  5. import logging.config
  6. import os
  7. import sys
  8. def setup_logging(log_level: str = None):
  9. """
  10. Configure logging for the application and all imported modules.
  11. This must be called BEFORE importing any modules that use logging,
  12. to ensure they all use the same logging configuration.
  13. Args:
  14. log_level: The logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL).
  15. If None, reads from CBS_LOG_LEVEL environment variable.
  16. """
  17. if log_level is None:
  18. log_level = os.getenv('CBS_LOG_LEVEL', default='INFO')
  19. # Configure logging with dictConfig for consistency with Flask app
  20. logging_config = {
  21. 'version': 1,
  22. 'disable_existing_loggers': False,
  23. 'formatters': {
  24. 'default': {
  25. 'format': (
  26. '[%(asctime)s] %(levelname)s in %(module)s: '
  27. '%(message)s'
  28. ),
  29. 'datefmt': '%Y-%m-%d %H:%M:%S',
  30. },
  31. 'detailed': {
  32. 'format': (
  33. '[%(asctime)s] %(levelname)s '
  34. '[%(name)s.%(funcName)s:%(lineno)d] %(message)s'
  35. ),
  36. 'datefmt': '%Y-%m-%d %H:%M:%S',
  37. },
  38. },
  39. 'handlers': {
  40. 'console': {
  41. 'class': 'logging.StreamHandler',
  42. 'stream': sys.stdout,
  43. 'formatter': 'default',
  44. 'level': log_level.upper(),
  45. },
  46. },
  47. 'root': {
  48. 'level': log_level.upper(),
  49. 'handlers': ['console'],
  50. },
  51. 'loggers': {
  52. 'uvicorn': {
  53. 'level': 'INFO',
  54. 'handlers': ['console'],
  55. 'propagate': False,
  56. },
  57. 'uvicorn.access': {
  58. 'level': 'INFO',
  59. 'handlers': ['console'],
  60. 'propagate': False,
  61. },
  62. 'uvicorn.error': {
  63. 'level': 'INFO',
  64. 'handlers': ['console'],
  65. 'propagate': False,
  66. },
  67. 'fastapi': {
  68. 'level': log_level.upper(),
  69. 'handlers': ['console'],
  70. 'propagate': False,
  71. },
  72. },
  73. }
  74. logging.config.dictConfig(logging_config)
  75. # Log that logging has been configured
  76. logger = logging.getLogger(__name__)
  77. logger.info(f"Logging configured with level: {log_level.upper()}")
  78. logger.info(f"Python version: {sys.version}")