fd_logging.py 1.8 KB

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