log_util.py 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import logging
  2. import time
  3. from common.yaml_util import get_project_path, read_config_yaml
  4. class LoggerUtil:
  5. def create_log(self, logger_name='log'):
  6. # 创建一个日志对象
  7. self.logger = logging.getLogger(logger_name)
  8. # 设置全局的日志级别(从低到高:debug调试<info信息<warning警告<error错误<critical严重)
  9. self.logger.setLevel(logging.DEBUG)
  10. if not self.logger.handlers:
  11. # ------文件日志------
  12. # 1创建文件日志路径
  13. self.file_log_path = get_project_path() + "/logs/" + read_config_yaml("log", "log_name") + str(
  14. int(time.time())) + ".log"
  15. # 2创建文件日志控制器
  16. self.file_hander = logging.FileHandler(self.file_log_path, encoding='UTF-8')
  17. # 3设置文件日志级别
  18. file_log_level = str(read_config_yaml("log", "log_level")).lower()
  19. if file_log_level == "debug":
  20. self.file_hander.setLevel(logging.DEBUG)
  21. elif file_log_level == "info":
  22. self.file_hander.setLevel(logging.INFO)
  23. elif file_log_level == "warning":
  24. self.file_hander.setLevel(logging.WARNING)
  25. elif file_log_level == "error":
  26. self.file_hander.setLevel(logging.ERROR)
  27. elif file_log_level == "critical":
  28. self.file_hander.setLevel(logging.CRITICAL)
  29. else:
  30. self.file_hander.setLevel(logging.DEBUG)
  31. # 4创建文件的格式
  32. self.file_hander.setFormatter(logging.Formatter(read_config_yaml("log", "log_format")))
  33. # 将文件日志的控制器加入日志对象
  34. self.logger.addHandler(self.file_hander)
  35. # 创建控制台日志
  36. # 1创建控制台日志控制器
  37. self.console_hander = logging.StreamHandler()
  38. # 2设置控制台日志级别
  39. console_log_level = str(read_config_yaml("log", "log_level")).lower()
  40. if console_log_level == "debug":
  41. self.console_hander.setLevel(logging.DEBUG)
  42. elif console_log_level == "info":
  43. self.console_hander.setLevel(logging.INFO)
  44. elif console_log_level == "warning":
  45. self.console_hander.setLevel(logging.WARNING)
  46. elif console_log_level == "error":
  47. self.console_hander.setLevel(logging.ERROR)
  48. elif console_log_level == "critical":
  49. self.console_hander.setLevel(logging.CRITICAL)
  50. else:
  51. self.console_hander.setLevel(logging.DEBUG)
  52. # 3创建控制台的日志格式
  53. self.console_hander.setFormatter(logging.Formatter(read_config_yaml("log", "log_format")))
  54. # 将控制台日志加入日志对象
  55. self.logger.addHandler(self.console_hander)
  56. # 返回包含文件日志控制器和控制台日志控制器的日志对象
  57. return self.logger
  58. # 错误日志的输出
  59. def error_log(message):
  60. LoggerUtil().create_log().error(message)
  61. raise Exception(message)
  62. # 信息日志的输出
  63. def logs(message):
  64. LoggerUtil().create_log().info(message)
  65. if __name__ == '__main__':
  66. error_log("车务通")