记录日志
import logging
class Log:
def __init__(self):
"""
初始化
"""
self.level = logging.INFO
self.t_fmt = "%Y-%m-%d %H:%M:%S"
self.l_fmt = "[%(asctime)s %(levelname)s] %(filename)s:%(lineno)s: %(message)s"
logging.basicConfig(level=self.level, datefmt=self.t_fmt, format=self.l_fmt)
self.logger = logging.getLogger(__name__)
def log2file(self, path, mode='a'):
"""
生成日志文件
:param path: 是否要生成日志文件, 完整路径(包含日志文件名)
:param mode: 日志文件记录模式, 追加(a) | 覆盖(w)
"""
try:
handler = logging.FileHandler(path, mode=mode, encoding='utf-8')
handler.setLevel(self.level)
fmt = logging.Formatter(fmt=self.l_fmt, datefmt=self.t_fmt)
handler.setFormatter(fmt)
self.logger.addHandler(handler)
self.logger.info("[日志] 生成日志文件 成功")
except Exception as e:
self.logger.error(f"[日志] 生成日志文件 失败 {e}")
def log(self):
return self.logger
if __name__ == '__main__':
log_path = "/Users/aiden/Desktop/log.log"
log = Log()
log = log.log()
log.info('[日志] 123')
log.error('[日志] 123')