import os import datetime import logging BASE_DIR = os.path.dirname(os.path.dirname(__file__)) time_now = datetime.datetime.now().strftime('%Y-%m-%d') class MyLogger(object): def __init__(self,log_file_path,logger_name): self.logger_name = logger_name self.log_file_path = log_file_path def getmylogger(self,level='DEBUG'): fmt = '%(asctime)s - %(funcName)s - %(levelname)s - %(message)s' # 设置日志格式 datefmt = '%Y-%m-%d %H:%M:%S' # 设置时间的格式 formatter = logging.Formatter(fmt=fmt,datefmt=datefmt) # 设置handler01 用于用输出到文件 handler_file = logging.FileHandler(self.log_file_path) # stdout to file handler_file.setLevel('DEBUG') #设置输出级别 handler_file.setFormatter(formatter) #设置输出格式 # 设置handler02 用于用输出到控制台 handler_stream = logging.StreamHandler() # stdout to console handler_stream.setLevel('DEBUG') handler_stream.setFormatter(formatter) logger = logging.getLogger(self.logger_name) logger.setLevel('DEBUG') # 设置了这个才会把debug以上的输出到控制台 logger.addHandler(handler_file) # 添加handler logger.addHandler(handler_stream) return logger if __name__ == '__main__': hhh1 = MyLogger(log_file_path='mylog01.log',logger_name='mylogger01').getmylogger() hhh1.debug('Im debug!!!!') hhh1.info('I am info!!!') hhh1.error('I am error!!!') hhh1.warning('Im crital!!!!')
日志模块logging
于 2023-04-14 01:40:14 首次发布