log.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import logging
  2. import sys
  3. import os
  4. from logging.handlers import RotatingFileHandler
  5. import threading
  6. class MyLogger(object):
  7. instance = None
  8. init_flag = None
  9. def __init__(self, name=""):
  10. """此处设计为,如果已经存在实例时,不再执行初始化"""
  11. if self.init_flag:
  12. return
  13. else:
  14. self.init_flag = True
  15. self.logger_lock = threading.Lock()
  16. self.name = name
  17. self.init()
  18. def init(self):
  19. # 创建日志器
  20. self.logger = logging.getLogger("图片抠图工具")
  21. self.logger.setLevel("DEBUG")
  22. if not os.path.exists("{}\log".format(os.getcwd())):
  23. os.mkdir("{}\log".format(os.getcwd()))
  24. # 定义日志处理器
  25. cl = logging.StreamHandler() # 将日志输出到终端
  26. fl = RotatingFileHandler("log\logging_text.log", mode="a", encoding="utf-8", maxBytes=10 * 1024 * 1024,
  27. backupCount=5) # 输出日志到文本
  28. # 定义初始化格式 # 定义两个日志布局
  29. fmt1 = ("%(asctime)s---%(name)s---%(message)s")
  30. fmt2 = ("%(asctime)s---%(lineno)d---%(name)s---%(message)s")
  31. # 创建初始化器
  32. a = logging.Formatter(fmt=fmt1)
  33. b = logging.Formatter(fmt=fmt2)
  34. # 添加处理器格式 将上面创建的初始化器添加
  35. cl.setFormatter(a)
  36. fl.setFormatter(b)
  37. # 将处理器添加到日志器
  38. self.logger.addHandler(cl)
  39. self.logger.addHandler(fl)
  40. sys.excepthook = self.handle_exception
  41. # 函数,用来记录系统报错
  42. def handle_exception(self, exc_type, exc_value, exc_traceback):
  43. if issubclass(exc_type, KeyboardInterrupt):
  44. sys.__excepthook__(exc_type, exc_value, exc_traceback)
  45. return
  46. self.logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
  47. def __new__(cls, *args, **kwargs):
  48. """如果当前没有实例时,调用父类__new__方法,生成示例,有则返回保存的内存地址。"""
  49. if not cls.instance:
  50. cls.instance = super().__new__(cls)
  51. return cls.instance
  52. # logger.debug("debug message")
  53. # logger.info("debug message")
  54. # logger.warning("warning message")
  55. # logger.error("error message")
  56. # logger.critical("critical message")