import logging import os def setup_logger(name, log_file, level=logging.INFO): """Function setup as many loggers as you want""" if not os.path.exists(os.path.dirname(log_file)): os.makedirs(os.path.dirname(log_file)) formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') handler = logging.FileHandler(log_file) handler.setFormatter(formatter) # 控制台是否输出日志信息 # stream_handler = logging.StreamHandler() # stream_handler.setFormatter(formatter) logger = logging.getLogger(name) logger.setLevel(level) logger.addHandler(handler) # 控制台 # logger.addHandler(stream_handler) # 刷新原有log文件 if os.path.exists(log_file): open(log_file, 'w').close() return logger """ 用法示例 """ def main(): log_file = "app.log" logger = setup_logger(__name__, log_file) logger.info("Application started.") logger.debug("Debug message.") logger.warning("Warning message.") logger.error("Error occurred.")