You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

199 satır
6.1KB

  1. # import logging
  2. # import sys
  3. # import os
  4. # from datetime import datetime, timedelta
  5. # LOG_DIR = "./logs" # 日志文件目录
  6. # LOG_RETENTION_DAYS = 7 # 日志保留天数
  7. # def _remove_old_logs(log_dir, retention_days):
  8. # """删除超过保留天数的日志文件"""
  9. # if not os.path.exists(log_dir):
  10. # os.makedirs(log_dir)
  11. # now = datetime.now()
  12. # for filename in os.listdir(log_dir):
  13. # file_path = os.path.join(log_dir, filename)
  14. # if os.path.isfile(file_path) and filename.startswith("run_") and filename.endswith(".log"):
  15. # # 提取文件日期
  16. # try:
  17. # log_date_str = filename[4:14]
  18. # log_date = datetime.strptime(log_date_str, "%Y-%m-%d")
  19. # if now - log_date > timedelta(days=retention_days):
  20. # os.remove(file_path)
  21. # print(f"删除旧日志: {filename}")
  22. # except ValueError:
  23. # continue
  24. # def _reset_logger(log):
  25. # """重置日志配置,移除旧的 Handler 并添加新的 Handler"""
  26. # for handler in log.handlers:
  27. # handler.close()
  28. # log.removeHandler(handler)
  29. # del handler
  30. # log.handlers.clear()
  31. # log.propagate = False
  32. # # 控制台输出的日志处理器
  33. # console_handle = logging.StreamHandler(sys.stdout)
  34. # console_handle.setFormatter(
  35. # logging.Formatter(
  36. # "[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d] - %(message)s",
  37. # datefmt="%Y-%m-%d %H:%M:%S",
  38. # )
  39. # )
  40. # # 生成带有当前日期的日志文件路径
  41. # date_str = datetime.now().strftime("%Y-%m-%d")
  42. # log_file_path = os.path.join(LOG_DIR, f"run_{date_str}.log")
  43. # # 文件日志处理器
  44. # file_handle = logging.FileHandler(log_file_path, encoding="utf-8")
  45. # file_handle.setFormatter(
  46. # logging.Formatter(
  47. # "[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d] - %(message)s",
  48. # datefmt="%Y-%m-%d %H:%M:%S",
  49. # )
  50. # )
  51. # # 将处理器添加到日志
  52. # log.addHandler(file_handle)
  53. # log.addHandler(console_handle)
  54. # # 删除旧的日志文件
  55. # _remove_old_logs(LOG_DIR, LOG_RETENTION_DAYS)
  56. # def setup_logging():
  57. # """设置日志配置"""
  58. # log = logging.getLogger("log")
  59. # _reset_logger(log)
  60. # log.setLevel(logging.INFO) # 日志级别
  61. # return log
  62. # def setup_logging():
  63. # """设置日志配置"""
  64. # log = logging.getLogger() # 获取 Flask 默认的日志记录器
  65. # _reset_logger(log)
  66. # log.setLevel(logging.INFO) # 设置日志级别为 INFO
  67. # return log
  68. # # 创建日志实例
  69. # logger = setup_logging()
  70. # def log_exception(sender, exception, **extra):
  71. # """记录异常日志"""
  72. # sender.logger.debug('处理过程发生异常: %s', exception)
  73. import logging
  74. import sys
  75. import os
  76. from datetime import datetime, timedelta
  77. # 日志文件目录
  78. LOG_DIR = "./logs"
  79. # 日志保留天数
  80. LOG_RETENTION_DAYS = 7
  81. def _remove_old_logs(log_dir, retention_days):
  82. """删除超过保留天数的日志文件"""
  83. if not os.path.exists(log_dir):
  84. os.makedirs(log_dir)
  85. now = datetime.now()
  86. for filename in os.listdir(log_dir):
  87. file_path = os.path.join(log_dir, filename)
  88. if os.path.isfile(file_path) and filename.startswith("run_") and filename.endswith(".log"):
  89. # 提取文件日期
  90. try:
  91. log_date_str = filename[4:14]
  92. log_date = datetime.strptime(log_date_str, "%Y-%m-%d")
  93. if now - log_date > timedelta(days=retention_days):
  94. os.remove(file_path)
  95. print(f"删除旧日志: {filename}")
  96. except ValueError:
  97. continue
  98. def _reset_logger(log):
  99. """重置日志配置,移除旧的 Handler 并添加新的 Handler"""
  100. for handler in log.handlers:
  101. handler.close()
  102. log.removeHandler(handler)
  103. del handler
  104. log.handlers.clear()
  105. log.propagate = False
  106. # 控制台输出的日志处理器
  107. console_handle = logging.StreamHandler(sys.stdout)
  108. console_handle.setFormatter(
  109. logging.Formatter(
  110. "[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d] - %(message)s",
  111. datefmt="%Y-%m-%d %H:%M:%S",
  112. )
  113. )
  114. # 生成带有当前日期的日志文件路径
  115. date_str = datetime.now().strftime("%Y-%m-%d")
  116. log_file_path = os.path.join(LOG_DIR, f"run_{date_str}.log")
  117. # 文件日志处理器
  118. file_handle = logging.FileHandler(log_file_path, encoding="utf-8")
  119. file_handle.setFormatter(
  120. logging.Formatter(
  121. "[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d] - %(message)s",
  122. datefmt="%Y-%m-%d %H:%M:%S",
  123. )
  124. )
  125. # 将处理器添加到日志
  126. log.addHandler(file_handle)
  127. log.addHandler(console_handle)
  128. # 删除旧的日志文件
  129. _remove_old_logs(LOG_DIR, LOG_RETENTION_DAYS)
  130. def setup_logging():
  131. """设置日志配置"""
  132. log = logging.getLogger() # 获取默认的日志记录器
  133. _reset_logger(log)
  134. log.setLevel(logging.INFO) # 设置日志级别为 INFO
  135. return log
  136. # 创建日志实例
  137. logger = setup_logging()
  138. def log_exception(sender, exception, **extra):
  139. """记录异常日志"""
  140. logger.error(f"处理过程发生异常: {exception}", exc_info=True)
  141. # FastAPI 日志配置示例
  142. def configure_fastapi_logging():
  143. """配置 FastAPI 的日志记录"""
  144. fastapi_logger = logging.getLogger("uvicorn")
  145. _reset_logger(fastapi_logger)
  146. fastapi_logger.setLevel(logging.INFO)
  147. # Celery 日志配置
  148. def configure_celery_logging():
  149. """配置 Celery 的日志记录"""
  150. celery_logger = logging.getLogger("celery")
  151. _reset_logger(celery_logger)
  152. celery_logger.setLevel(logging.INFO)
  153. # Celery RedBeat 日志配置
  154. def configure_redbeat_logging():
  155. """配置 Celery RedBeat 的日志记录"""
  156. redbeat_logger = logging.getLogger("redbeat")
  157. _reset_logger(redbeat_logger)
  158. redbeat_logger.setLevel(logging.INFO)
  159. # 配置 FastAPI 日志
  160. configure_fastapi_logging()
  161. # 配置 Celery 日志
  162. configure_celery_logging()
  163. # 配置 Redbeat 日志
  164. configure_redbeat_logging()