logging.py 1.8 KB

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