import logging import os from datetime import datetime class Log(): def __init__(self, logger_name='my_logger'): self.logger = logging.getLogger(logger_name) if self.logger.hasHandlers(): self.logger.handlers.clear() self.logger.setLevel(logging.INFO) # 定义固定日志路径 self.log_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'logs') self.log_file = os.path.join(self.log_dir, 'm3u8_download.log') if not os.path.exists(self.log_dir): os.makedirs(self.log_dir) self._setup_handlers() def _setup_handlers(self): """初始化日志处理器""" # 文件处理器(固定文件名) fh = logging.FileHandler(self.log_file, 'a', encoding='utf-8') fh.setLevel(logging.INFO) # 控制台处理器 ch = logging.StreamHandler() ch.setLevel(logging.INFO) # 统一格式器 formatter = logging.Formatter( '[%(asctime)s] %(filename)s line:%(lineno)d [%(levelname)s]%(message)s', datefmt="%Y-%m-%d %H:%M:%S" ) fh.setFormatter(formatter) ch.setFormatter(formatter) # 添加处理器 self.logger.addHandler(fh) self.logger.addHandler(ch) # 移除日期检查相关方法 def info(self, msg, *args, ** kwargs): self.logger.info(msg, *args, ** kwargs) def error(self, msg, *args, ** kwargs): self.logger.error(msg, *args, ** kwargs) def warning(self, msg, *args, ** kwargs): self.logger.warning(msg, *args, ** kwargs) if __name__ == "__main__": log = Log() log.info("---测试开始----") log.error("操作步骤1,2,3") log.warning("----测试结束----")