log_utils.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import logging.handlers
  2. import logging
  3. import os
  4. import sys
  5. # 提供日志功能
  6. class logFactory():
  7. def __init__(self, name):
  8. # 初始化logger
  9. self.log = logging.getLogger(name)
  10. # 设置日志文件保存路径,common同级目录中的logs文件夹
  11. self.logpath = os.path.abspath(os.path.join(os.getcwd(), "logs"))
  12. if not os.path.exists(self.logpath):
  13. os.makedirs(self.logpath)
  14. # 日志文件的绝对路径
  15. self.logname = os.path.join(self.logpath, 'app.log')
  16. # print(f"日志保存路径{logpath}")
  17. # 设置日志文件容量,转换为字节
  18. self.logsize = 1024 * 1024 * int(8) # 8M
  19. # 设置日志文件保存个数
  20. self.lognum = int(3)
  21. # 日志格式,可以根据需要设置
  22. self.fmt = logging.Formatter('[%(asctime)s]-[%(levelname)s]-[%(filename)s]-[line:%(lineno)d]: %(message)s',
  23. '%Y-%m-%d %H:%M:%S')
  24. # 日志输出到文件,设置日志名称,大小,保存个数,编码
  25. self.handle1 = logging.handlers.RotatingFileHandler(self.logname, maxBytes=self.logsize,
  26. backupCount=self.lognum, encoding='utf-8')
  27. self.handle1.setFormatter(self.fmt)
  28. self.log.addHandler(self.handle1)
  29. # 日志输出到屏幕,便于实时观察
  30. self.handle2 = logging.StreamHandler(stream=sys.stdout)
  31. self.handle2.setFormatter(self.fmt)
  32. self.log.addHandler(self.handle2)
  33. # 设置日志等级,这里设置为INFO,表示只有INFO级别及以上的会打印
  34. self.log.setLevel(logging.INFO)
  35. # 日志接口,可根据需要定义更多接口
  36. @classmethod
  37. def info(self, msg):
  38. self.log.info(msg)
  39. return
  40. @classmethod
  41. def warning(self, msg):
  42. self.log.warning(msg)
  43. return
  44. @classmethod
  45. def error(cls, msg):
  46. cls.log.error(msg)
  47. return
  48. @classmethod
  49. def debug(cls, msg):
  50. cls.log.debug(msg)
  51. return