logging日志
logging介绍
python的logging模块提供了通用的日志系统,可以方便第三方模块或者是应用使用,这个模块提供不同的日志级别,并可采用不同的方式记录日志。
# -*- coding: UTF-8 -*- import os import logging import time from logging.handlers import TimedRotatingFileHandler from concurrent_log_handler import ConcurrentRotatingFileHandler class Logger(): @staticmethod def make_dir(make_dir_path): path = make_dir_path.strip() if not os.path.exists(path): os.makedirs(path) return path def save_logger(self, server_name, prefix_logger_name, log_dir_name = None): ''' :param server_name: 服务名称 :param prefix_logger_name: 日志文件前缀,后面会自动加日期,如prefix_logger_name-2020-02-02.log :param log_dir_name: 日志文件存放目录 :return: logging对象 ''' _logger = logging.getLogger(server_name) log_file_name = prefix_logger_name + "-" + time.strftime('%Y-%m-%d', time.localtime(time.time())) + '.log' #如果不存在目錄 if not log_dir_name: #os.path.dirname獲取當前文件的路徑,os.pardir返回上一級的路徑,os.path.abspath方向取反(/改\) log_file_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) + os.sep + "logs" else: log_file_folder = log_dir_name self.make_dir(log_file_folder) log_file_str = log_file_folder + os.sep + log_file_name print(log_file_str) log_level = logging.DEBUG handler = ConcurrentRotatingFileHandler(log_file_str, maxBytes=1024 * 1024 * 100, backupCount=1000, encoding='UTF-8') handler.setLevel(log_level) #asctime, thread, levelname, message, args logging_format = logging.Formatter('%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s') handler.setFormatter(logging_format) _logger.disabled = False _logger.level = log_level _logger.addHandler(handler) return _logger logger_obj = Logger() send_logger = logger_obj.save_logger("Trade", "log", 'E:\Code').info('test3') send_logger = logger_obj.save_logger("Trade", "log", 'E:\Code').error('test4') send_logger = logger_obj.save_logger("Trade", "log", 'E:\Code').debug('test5')
执行结果