log_ware.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3. #
  4. #
  5. # author: Scott Chen
  6. # date: 2020-01-03
  7. import os
  8. import time
  9. import logging
  10. from logging.handlers import RotatingFileHandler
  11. class LogWare(object):
  12. # ---------- 创建日志对象的单例模式 ----------
  13. __instance = None
  14. def __new__(cls, *args, **kwargs):
  15. if not cls.__instance:
  16. cls.__instance = super().__new__(cls)
  17. return cls.__instance
  18. # ---------- 日志类构造方法 ----------
  19. def __init__(self, level='DEBUG'):
  20. if '_logger' not in self.__dict__:
  21. # -------------------- 日志配置 --------------------
  22. # 日志路径
  23. self.__log_path = 'd:/data/logs/'
  24. # 项目名作为日志目录
  25. self.__project_name = 'idcard_reader_web'
  26. # 日志文件名
  27. self.__log_file_prefix = 'idcard_reader_web_log'
  28. # 日志级别,DEBUG,INFO,WARNING,ERROR,CRITICAL
  29. self.__log_level = level
  30. # -------------------- 日志路径文件创建 --------------------
  31. self.__log_size = 3 * 1024 * 1024
  32. self.__backup_count = 100
  33. self.__formatter = logging.Formatter('1[%(asctime)s][%(threadName)s][%(levelname)s][%(filename)s][%(lineno)d] %(message)s', '%Y-%m-%d %H:%M:%S')
  34. self.__timestamp = time.strftime("%Y-%m-%d", time.localtime())
  35. # 日志除文件名之外的路径
  36. self.__log_path_dict = {
  37. 'debug': os.path.join(self.__log_path, self.__project_name, 'debug'),
  38. 'info': os.path.join(self.__log_path, self.__project_name, 'info'),
  39. 'warning': os.path.join(self.__log_path, self.__project_name, 'warning'),
  40. 'error': os.path.join(self.__log_path, self.__project_name, 'error'),
  41. 'critical': os.path.join(self.__log_path, self.__project_name, 'critical'),
  42. }
  43. # 日志全路径
  44. self.__log_full_path_dict = {}
  45. for (k, v) in self.__log_path_dict.items():
  46. self.__log_full_path_dict[k] = os.path.join(v, self.__log_file_prefix + '_' + self.__timestamp + '_' + k + '.log')
  47. # 创建日志目录
  48. for (k, v) in self.__log_path_dict.items():
  49. if os.path.exists(v) and os.path.isdir(v):
  50. pass
  51. else:
  52. os.makedirs(v)
  53. # 日志对象
  54. # self.__logger = logging
  55. # -------------------- 构造日志对象 --------------------
  56. # 控制台
  57. console_handler = logging.StreamHandler()
  58. console_handler.setFormatter(self.__formatter)
  59. # 此处通过文件大小截断日志文件,如果想要通过时间截断,可以使用 TimedRotatingFileHandler 这个类
  60. debug_handler = logging.handlers.RotatingFileHandler(
  61. filename=self.__log_full_path_dict['debug'],
  62. mode='w',
  63. maxBytes=self.__log_size,
  64. encoding='utf-8',
  65. backupCount=self.__backup_count
  66. )
  67. debug_handler.setFormatter(self.__formatter)
  68. info_handler = logging.handlers.RotatingFileHandler(
  69. filename=self.__log_full_path_dict['info'],
  70. mode='w',
  71. maxBytes=self.__log_size,
  72. encoding='utf-8',
  73. backupCount=self.__backup_count
  74. )
  75. info_handler.setFormatter(self.__formatter)
  76. warning_handler = logging.handlers.RotatingFileHandler(
  77. filename=self.__log_full_path_dict['warning'],
  78. mode='w',
  79. maxBytes=self.__log_size,
  80. encoding='utf-8',
  81. backupCount=self.__backup_count
  82. )
  83. warning_handler.setFormatter(self.__formatter)
  84. error_handler = logging.handlers.RotatingFileHandler(
  85. filename=self.__log_full_path_dict['error'],
  86. mode='w',
  87. maxBytes=self.__log_size,
  88. encoding='utf-8',
  89. backupCount=self.__backup_count
  90. )
  91. error_handler.setFormatter(self.__formatter)
  92. critical_handler = logging.handlers.RotatingFileHandler(
  93. filename=self.__log_full_path_dict['critical'],
  94. mode='w',
  95. maxBytes=self.__log_size,
  96. encoding='utf-8',
  97. backupCount=self.__backup_count
  98. )
  99. critical_handler.setFormatter(self.__formatter)
  100. # 日志文件输出
  101. logger = logging.getLogger()
  102. logger.addHandler(console_handler)
  103. logger.addHandler(debug_handler)
  104. logger.setLevel(self.__log_level)
  105. self._logger = logger
  106. # 返回日志对象
  107. def return_logger(self):
  108. return self._logger
  109. def get_logger():
  110. return LogWare().return_logger()
  111. # ########## 单元测试 ##########
  112. if __name__ == '__main__':
  113. # 外部使用时,引入
  114. # from log_ware import get_logger
  115. # 生成日志对象
  116. logger = get_logger()
  117. i = 0
  118. while True:
  119. logger.debug("level debug %s %s %d", 'aaaa', 'bbb', 10)
  120. logger.info("level info")
  121. logger.warning('level warning')
  122. logger.error("level error")
  123. logger.critical('level critical')
  124. i += 1
  125. if i == 1: break