赞
踩
参数说明:
backupCount=3 :保存3天的日志
when=“MIDNIGHT” : 每天晚上零点会保存一个新的日志
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : mt_log.py @Time : 2022/09/26 21:12:03 @Author : YuanPangZi @Version : 1.0 @Contact : https://blog.csdn.net/qq_36389249?spm=1000.2115.3001.5343 @License : bf24ebed572b07451d0342fc762710a6 @Desc : 572b07451d0342fc ''' # here put the import lib import logging from logging import handlers import os import time #日志的设置 class Logger(object): level_relations = { "debug": logging.DEBUG, "info": logging.INFO, "warning": logging.WARNING, "error": logging.ERROR, "critical": logging.CRITICAL } def __init__(self, filename="MtTer.log", level="info", when="D", backupCount=3, fmt="%(asctime)s - %(pathname)s[line:%(lineno)d] - %" "(levelname)s: %(message)s"): format_str = logging.Formatter(fmt) streamHandler = logging.StreamHandler() streamHandler.setFormatter(format_str) log_dir=os.path.join(os.path.dirname(os.path.dirname(__file__)),"Mtlogs") today = time.strftime('%Y%m%d', time.localtime(time.time())) full_path=os.path.join(log_dir,today) if not os.path.exists(full_path): os.makedirs(full_path) log_path=os.path.join(full_path,filename) fileHandler = handlers.TimedRotatingFileHandler(filename=log_path, when=when, backupCount=backupCount, encoding="utf-8") fileHandler.setFormatter(format_str) self.logger = logging.getLogger(log_path) self.logger.setLevel(self.level_relations.get(level)) self.logger.addHandler(streamHandler) self.logger.addHandler(fileHandler) log = Logger(level="info", when="MIDNIGHT").logger def Mtlog(func): logger = logging.getLogger(__name__) logger.setLevel('DEBUG') formatter = logging.Formatter( "%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s") ch = logging.StreamHandler() ch.setFormatter(formatter) logger.addHandler(ch) log_dir=os.path.join(os.path.dirname(os.path.dirname(__file__)),"Mtlogs") today = time.strftime('%Y%m%d', time.localtime(time.time())) full_path=os.path.join(log_dir,today) if not os.path.exists(full_path): os.makedirs(full_path) log_path=os.path.join(full_path,"MtTer.log") file_handler = logging.FileHandler(log_path,encoding="utf8") file_handler.setFormatter(formatter) logger.addHandler(file_handler) def inner(*args, **kwargs): try: res = func(*args, **kwargs) logger.debug(f"func: {func.__name__} {args} - > {res}") return res except Exception as e: res = func(*args, **kwargs) logger.error(f"func: {func.__name__} {args} - > {res}") return res return inner
''' @File : main.py @Time : 2022/10/11 15:25:28 @Author : YuanPangZi @Version : 1.0 @Contact : https://blog.csdn.net/qq_36389249?spm=1000.2115.3001.5343 @License : bf24ebed572b07451d0342fc762710a6 @Desc : 572b07451d0342fc ''' # here put the import lib from mt_log import * @Mtlog def test(a, b): print(a, b) log.info("test!!!") return a,b if __name__ == "__main__": test(1, 2)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。