logging.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
  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. import time
  15. import os
  16. import sys
  17. import colorama
  18. from colorama import init
  19. import paddlex
  20. import paddle
  21. init(autoreset=True)
  22. levels = {0: 'ERROR', 1: 'WARNING', 2: 'INFO', 3: 'DEBUG'}
  23. def log(level=2, message="", use_color=False):
  24. if paddle.distributed.get_rank() == 0:
  25. current_time = time.time()
  26. time_array = time.localtime(current_time)
  27. current_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
  28. if paddlex.log_level >= level:
  29. if use_color:
  30. print("\033[1;31;40m{} [{}]\t{}\033[0m".format(
  31. current_time, levels[level], message).encode("utf-8")
  32. .decode("latin1"))
  33. else:
  34. print("{} [{}]\t{}".format(current_time, levels[
  35. level], message).encode("utf-8").decode("latin1"))
  36. sys.stdout.flush()
  37. def debug(message="", use_color=False):
  38. log(level=3, message=message, use_color=use_color)
  39. def info(message="", use_color=False):
  40. log(level=2, message=message, use_color=use_color)
  41. def warning(message="", use_color=True):
  42. log(level=1, message=message, use_color=use_color)
  43. def error(message="", use_color=True, exit=True):
  44. log(level=0, message=message, use_color=use_color)
  45. if exit:
  46. sys.exit(-1)