log.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import sys
  4. from logging import DEBUG
  5. from logging import Formatter
  6. from logging import StreamHandler
  7. from logging import getLogger
  8. from logging.handlers import RotatingFileHandler
  9. def init_logging(module_name, log_file, level=DEBUG, max_bytes=65536000,
  10. backup_count=3):
  11. """get the logger for the module_name and the log_file
  12. Args:
  13. module_name (str): the module name
  14. log_file (str): the log file
  15. level:
  16. max_bytes: 65536000, 64MB
  17. backup_count:
  18. Returns:
  19. Logger: the logger
  20. """
  21. logger = getLogger(module_name)
  22. if logger.handlers:
  23. return logger
  24. logger.setLevel(level)
  25. logger.propagate = True
  26. handler = RotatingFileHandler(
  27. filename=log_file, maxBytes=max_bytes, backupCount=backup_count)
  28. formatter = Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s")
  29. handler.setFormatter(formatter)
  30. logger.addHandler(handler)
  31. handler = StreamHandler(sys.stdout)
  32. handler.setFormatter(formatter)
  33. logger.addHandler(handler)
  34. return logger