python log日誌(二)
阿新 • • 發佈:2019-02-01
上一篇文章已經介紹log簡單使用方法,本文介紹下另一種用法,可以列印日誌,同時記錄日誌檔案,可以控制日誌顏色
import inspect import logging import logging.handlers import os from colorama import Fore, Style logger_dict = {} class LyrebirdLogger: def __init__(self, name): file_fmt = '[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s' date_fmt = '%Y-%m-%d %H:%M:%S' level = logging.DEBUG log_file = os.path.join(os.path.join(os.path.expanduser('~'), '.yourtoolpath'), 'log.log') mode = 'a' encoding = 'UTF-8' max_bytes = 1024*1024*2 back_count = 1 file_handler = create_file_handler(level, file_fmt, date_fmt, log_file, mode, max_bytes, back_count, encoding) self.name = name self.logger = logging.getLogger(name) self.logger_prefix = get_logger_prefix() self.logger.setLevel(level) self.logger.addHandler(file_handler) def debug(self, *msg): print(tag_blue(self.logger_prefix), *msg) self.logger.debug(get_msg(tag_blue(self.logger_prefix), *msg)) def info(self, *msg): print(tag_green(self.logger_prefix), *msg) self.logger.info(get_msg(tag_green(self.logger_prefix), *msg)) def warning(self, *msg): print(tag_yellow(self.logger_prefix), *msg) self.logger.warning(get_msg(tag_yellow(self.logger_prefix), *msg)) def error(self, *msg): print(tag_red(self.logger_prefix), *msg) self.logger.error(get_msg(tag_red(self.logger_prefix), *msg)) def critical(self, *msg): print(tag_red(self.logger_prefix), *msg) self.logger.critical(get_msg(tag_red(self.logger_prefix), *msg)) def tag_green(msg): if not msg: return '' return f'{Fore.GREEN}{msg}{Style.RESET_ALL}' def tag_yellow(msg): if not msg: return '' return f'{Fore.YELLOW}{msg}{Style.RESET_ALL}' def tag_blue(msg): if not msg: return '' return f'{Fore.BLUE}{msg}{Style.RESET_ALL}' def tag_red(msg): if not msg: return '' return f'{Fore.RED}{msg}{Style.RESET_ALL}' def tag_cyan(msg): if not msg: return '' return f'{Fore.CYAN}{msg}{Style.RESET_ALL}' def get_msg(*msg): func_name = get_current_func_name() line_num = get_current_line_num() message = '[%s] [%d] ' % (func_name, line_num) for i in range(len(msg)): message = message + str(msg[i]) + ' ' return message def create_file_handler(level, fmt, date_fmt, log_file, mode, max_bytes, back_count, encoding): file_handler = logging.handlers.RotatingFileHandler(log_file, mode, max_bytes, back_count, encoding) file_handler.setLevel(level) formatter = logging.Formatter(fmt, date_fmt) file_handler.setFormatter(formatter) return file_handler def get_logger_prefix(): """ 獲取top_module_name,拼接日誌使用 :return: 最外層包名 """ stack = inspect.stack() caller_module = inspect.getmodule(stack[1].frame) caller_module_name = caller_module.__name__ if caller_module_name.find('.') > 0: caller_top_module_name = caller_module_name.split('.')[0] else: caller_top_module_name = caller_module_name return caller_top_module_name def get_current_line_num(): return inspect.stack()[3][2] def get_current_func_name(): return inspect.stack()[3][3] def get_logger(name): logger = logger_dict.get(name) if not logger: logger = LyrebirdLogger(name) logger_dict[name] = logger return logger
需要日誌時,呼叫即可
_logger = get_logger('mock_server')
_logger.info('...')