说明
- 利用logging模块做了一个类和一个装饰器,可以将代码直接拷贝到自己的工程中使用,测试代码和说明下面也都有。
- 日志会自动生成文件并且按照日期存储
- 日志会同时输出到控制台和文件中
- 使用时可以看使用示例
参数说明:
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)
运行结果