通过python自带的logging模块进行封装
代码示例:
import logging import os import time from common.config_utils import local_config current_path = os.path.dirname(__file__) log_file_path = os.path.join(current_path,'../logs') class LogUtils: def __init__(self,logger = None): # 创建日志对象logger self.logger = logging.getLogger(logger) # 设置日志级别 self.logger.setLevel(local_config.get_log_level) """在文件中输出日志""" # 日志文件名称显示一天的日志 self.log_name = os.path.join(log_file_path,"UI_Test_%s"%time.strftime('%Y_%m_%d')) # 创建文件处理程序并实现追加 self.file_log = logging.FileHandler(self.log_name,'a',encoding='utf-8') # 设置日志文件里的级别 self.file_log.setLevel(local_config.get_log_level) # 设置日志文件里的格式 formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s') self.file_log.setFormatter(formatter) # 把日志信息输出到文件中 self.logger.addHandler(self.file_log) # 关闭文件 self.file_log.close() """在控制台输出日志""" # 日志在控制台 self.console = logging.StreamHandler() # 设置日志级别 self.console.setLevel(local_config.get_log_level) # 设置日志格式 self.console.setFormatter(formatter) # 把日志信息输出到控制台 self.logger.addHandler(self.console) # 关闭控制台 self.console.close() def get_log(self): return self.logger logger = LogUtils().get_log() if __name__ == '__main__': logger.info('123') logger.error('error')
展示结果:
下载第三方插件 nb-log;
代码示例:
from nb_log import LogManager logger = LogManager('p7p8').get_logger_and_add_handlers(is_add_stream_handler=True, log_path='../logs/', log_filename="test.log", log_level_int=10) logger.info('111') logger.error('error')
展示结果: