No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

72 líneas
2.1KB

  1. import logging
  2. import sys
  3. from datetime import datetime, timedelta
  4. import os
  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. for handler in log.handlers:
  26. handler.close()
  27. log.removeHandler(handler)
  28. del handler
  29. log.handlers.clear()
  30. log.propagate = False
  31. console_handle = logging.StreamHandler(sys.stdout)
  32. console_handle.setFormatter(
  33. logging.Formatter(
  34. "[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d] - %(message)s",
  35. datefmt="%Y-%m-%d %H:%M:%S",
  36. )
  37. )
  38. # 获取当前日期并将其加入日志文件名
  39. date_str = datetime.now().strftime("%Y-%m-%d")
  40. log_file_path = os.path.join(LOG_DIR, f"run_{date_str}.log")
  41. # 日志文件句柄
  42. file_handle = logging.FileHandler(log_file_path, encoding="utf-8")
  43. file_handle.setFormatter(
  44. logging.Formatter(
  45. "[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d] - %(message)s",
  46. datefmt="%Y-%m-%d %H:%M:%S",
  47. )
  48. )
  49. log.addHandler(file_handle)
  50. log.addHandler(console_handle)
  51. # 清理旧日志
  52. _remove_old_logs(LOG_DIR, LOG_RETENTION_DAYS)
  53. def _get_logger():
  54. log = logging.getLogger("log")
  55. _reset_logger(log)
  56. log.setLevel(logging.INFO)
  57. return log
  58. # 日志句柄
  59. logger = _get_logger()