logger.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. # --------------------------------------------------------
  2. # Swin Transformer
  3. # Copyright (c) 2021 Microsoft
  4. # Licensed under The MIT License [see LICENSE for details]
  5. # Written by Ze Liu
  6. # --------------------------------------------------------
  7. import os
  8. import sys
  9. import logging
  10. import functools
  11. from termcolor import colored
  12. @functools.lru_cache()
  13. def create_logger(output_dir, dist_rank=0, name=''):
  14. # create logger
  15. logger = logging.getLogger(name)
  16. logger.setLevel(logging.DEBUG)
  17. logger.propagate = False
  18. # create formatter
  19. fmt = '[%(asctime)s %(name)s] (%(filename)s %(lineno)d): %(levelname)s %(message)s'
  20. color_fmt = colored('[%(asctime)s %(name)s]', 'green') + \
  21. colored('(%(filename)s %(lineno)d)', 'yellow') + ': %(levelname)s %(message)s'
  22. # create console handlers for master process
  23. if dist_rank == 0:
  24. console_handler = logging.StreamHandler(sys.stdout)
  25. console_handler.setLevel(logging.DEBUG)
  26. console_handler.setFormatter(
  27. logging.Formatter(fmt=color_fmt, datefmt='%Y-%m-%d %H:%M:%S'))
  28. logger.addHandler(console_handler)
  29. # create file handlers
  30. file_handler = logging.FileHandler(os.path.join(output_dir, f'log_rank{dist_rank}.txt'), mode='a')
  31. file_handler.setLevel(logging.DEBUG)
  32. file_handler.setFormatter(logging.Formatter(fmt=fmt, datefmt='%Y-%m-%d %H:%M:%S'))
  33. logger.addHandler(file_handler)
  34. return logger