You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

log.py 2.6 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ===========================================================================
  15. """Logger."""
  16. import os
  17. import sys
  18. import logging
  19. from datetime import datetime
  20. logger_name_1 = 'ds-cnn'
  21. class LOGGER(logging.Logger):
  22. '''Build logger.'''
  23. def __init__(self, logger_name):
  24. super(LOGGER, self).__init__(logger_name)
  25. console = logging.StreamHandler(sys.stdout)
  26. console.setLevel(logging.INFO)
  27. formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(message)s')
  28. console.setFormatter(formatter)
  29. self.addHandler(console)
  30. def setup_logging_file(self, log_dir):
  31. if not os.path.exists(log_dir):
  32. os.makedirs(log_dir, exist_ok=True)
  33. log_name = datetime.now().strftime('%Y-%m-%d_time_%H_%M_%S')
  34. self.log_fn = os.path.join(log_dir, log_name)
  35. fh = logging.FileHandler(self.log_fn)
  36. fh.setLevel(logging.INFO)
  37. formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(message)s')
  38. fh.setFormatter(formatter)
  39. self.addHandler(fh)
  40. def info(self, msg, *args, **kwargs):
  41. if self.isEnabledFor(logging.INFO):
  42. self._log(logging.INFO, msg, args, **kwargs)
  43. def save_args(self, args):
  44. self.info('Args:')
  45. args_dict = vars(args)
  46. for key in args_dict.keys():
  47. self.info('--> %s: %s', key, args_dict[key])
  48. self.info('')
  49. def important_info(self, msg, *args, **kwargs):
  50. if self.isEnabledFor(logging.INFO):
  51. line_width = 2
  52. important_msg = '\n'
  53. important_msg += ('*' * 70 + '\n') * line_width
  54. important_msg += ('*' * line_width + '\n') * 2
  55. important_msg += '*' * line_width + ' ' * 8 + msg + '\n'
  56. important_msg += ('*' * line_width + '\n') * 2
  57. important_msg += ('*' * 70 + '\n') * line_width
  58. self.info(important_msg, *args, **kwargs)
  59. def get_logger(path):
  60. logger = LOGGER(logger_name_1)
  61. logger.setup_logging_file(path)
  62. return logger