#coding:utf-8 import logging import sys import os import datetime from logging import handlers class Logger(object): def __init__(self,name): LOGGING_TO_CONSOLE=True LOGGING_LEVEL = logging.DEBUG LOGGING_FORMATTER='%(asctime)s|%(filename)s %(funcName)s|line:%(lineno)d|%(levelname)s|%(message)s' logger = logging.getLogger(name) logger.setLevel(LOGGING_LEVEL) path=os.path.abspath("../log") data=datetime.date.today() filename=os.path.join(path,str(data).replace("-","")+".log") if not os.path.isdir(path): os.mkdir(path) formatter = logging.Formatter(LOGGING_FORMATTER,datefmt='%Y-%m-%d %X') # file_handler = handlers.TimedRotatingFileHandler(filename=filename, when="h", interval=1, backupCount=10) # file_handler.suffix = "%Y.%m.%d_%H.log" # file_handler.setFormatter(formatter) # logger.addHandler(file_handler) handler = handlers.RotatingFileHandler(filename, mode='a+',maxBytes=1024, backupCount=10) handler.setFormatter(formatter) logger.addHandler(handler) if LOGGING_TO_CONSOLE: stream_handler = logging.StreamHandler(sys.stderr) stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) self.logger = logger def getLogger(self): return self.logger
[test.py]
from logger import Logger logger = Logger("my_log").getLogger() def test(): try: b=9*9 4/0 logger.info("b={}".format(b)) except Exception as e: print("except:{}".format(e)) logger.error(e) test() #2022-07-27 14:43:09|tests.py test|line:13|INFO|b=81 #2022-07-27 14:43:14|tests.py test|line:16|INFO|division by zero