python 记录日志
2020-05-12 python 1041
import sys import time def Singletonfunc(cls): _instance = {} def _singleton(*args, **kargs): if cls not in _instance: _instance[cls] = cls(*args, **kargs) return _instance[cls] return _singleton @Singletonfunc class Log: def __init__(self): self.file = "log.txt" def record(self, msg, type="info"): now = time.strftime("%Y-%m-%d %H:%M:%S") # __file__ 当前文件 # sys._getframe().f_lineno 当前行 content = "[{0}] {1} file:{2} line:{3}:{4}\n".format(type, now, __file__, sys._getframe().f_lineno, msg) # print(content) with open(self.file, "a+", encoding="utf-8") as f: f.write(content) if __name__ == "__main__": Log().record("test 111")
Error.py
import time, sys from Log import Log def Singletonfunc(cls): _instance = {} def _singleton(*args, **kargs): if cls not in _instance: _instance[cls] = cls(*args, **kargs) return _instance[cls] return _singleton @Singletonfunc class Error: def trigger(self, msg): now = time.strftime("%Y-%m-%d %H:%M:%S") # __file__ 当前文件 # sys._getframe().f_lineno 当前行 content = "[error] {0} file:{1} line:{2}:{3}\n".format(now, __file__, sys._getframe().f_lineno, msg) print(content) Log().record(str(msg), "error") if __name__ == "__main__": Error().trigger("test 111")
#封装系统的logging
import logging.handlers def Singletonfunc(cls): _instance = {} def _singleton(*args, **kargs): if cls not in _instance: _instance[cls] = cls(*args, **kargs) return _instance[cls] return _singleton @Singletonfunc class Logger: def __init__(self): self.file = "./data/test.log" logger = logging.getLogger() #hdlr = logging.handlers.TimedRotatingFileHandler(filename=self.file, when='M', interval=5, backupCount=100,encoding="utf-8") formatter = logging.Formatter("%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S") hdlr = logging.FileHandler(filename=self.file, mode="a+", encoding='utf-8') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.INFO) self.logging = logger def instance(self): return self.logging # def info(self, msg): # return self.logging.info(msg) # # def warning(self, msg): # return self.logging.warning(msg) # # def debug(self, msg): # return self.logging.debug(msg) # # def error(self, msg): # return self.logging.error(msg) # # def critical(self, msg): # return self.logging.critical(msg) def Log(): return Logger().instance() if __name__ == "__main__": Log().info("test 111")
很赞哦! (0)
相关文章
文章评论
-
-
-
0条评论