#下列代码仅实现了,函数调用时计入 all.log 日志;
import datetime
import logging
import logging.handlers
from functools import wraps
# 带参数的装饰器,记录日志到日志文件
def logit(logfile='../log/all.log'):
def logging_decorator(func):
@wraps(func)
def logging_function(*args, **kwargs):
log_string = func.__name__ + " was called"
logging.basicConfig(format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s',level=logging.DEBUG)
logger = logging.getLogger()
rf_handler = logging.handlers.TimedRotatingFileHandler(logfile, when='midnight', interval=1, backupCount=7, atTime=datetime.time(0, 0, 0, 0))
rf_handler.setLevel(logging.INFO)
rf_handler.setFormatter(logging.Formatter("%(asctime)s -%(filename)s[:%(lineno)d] - %(levelname)s: %(message)s"))
f_handler = logging.FileHandler(logfile)
f_handler.setLevel(logging.ERROR)
f_handler.setFormatter(logging.Formatter("%(asctime)s - %(pathname)s[:%(lineno)d] - %(levelname)s: %(message)s"))
logger.addHandler(rf_handler)
logger.addHandler(f_handler)
logging.info(log_string)
return func(*args, **kwargs)
return logging_function
return logging_decorator
#不带参数使用
@logit()
def myfunc1():
pass
#带参数使用
@logit(logfile='../venv/OutLog/func2.log')
def myfunc2():
pass
if __name__ == '__main__':
myfunc1()
myfunc2()