效果

系统中已内置了logging日志管理模块,但是该模块功能较多,我也找不到输出颜色的配置,所以直接自己写一个简单的日志模块,目前暂不考虑输出到文件功能,效果如下:

在这里插入图片描述

源码

#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
@File    :   logger.py
@Time    :   2022-10-19 16:01
@Author  :   坐公交也用券
@Version :   1.0
@Contact :   faith01238@hotmail.com
@Homepage : https://liumou.site
@Desc    :   当前文件作用
"""
from os import path, getenv
from colorama import Fore, Style
from datetime import datetime
import inspect


class Loger:
	def __init__(self, file=None):
		"""
		初始化日志模块
		:param file: 设置日志文件
		"""
		if file is None:
			file = path.join(getenv("HOME"), 'plbm.log')
		self.file = file
		self.date = str(datetime.now()).split('.')[0]

	def _get_time(self):
		self.date = str(datetime.now()).split('.')[0]

	def info(self, msg):
		"""
		打印信息
		:param msg: 打印内容
		:return:
		"""
		fun_info = inspect.getframeinfo(inspect.currentframe().f_back)
		line_ = fun_info[1]
		module_name = fun_info[2]
		filename = fun_info[0]
		filename = str(filename).split('/')[-1]
		self._get_time()
		msg = self.date + " 文件: " + filename + "  行: " + str(line_) + " 函数: " + module_name + " - INFO : " + msg
		mess = str(Fore.GREEN + msg + Style.RESET_ALL)
		print(mess)

	def debug(self, msg):
		"""
		打印信息
		:param msg: 打印内容
		:return:
		"""
		fun_info = inspect.getframeinfo(inspect.currentframe().f_back)
		line_ = fun_info[1]
		module_name = fun_info[2]
		filename = fun_info[0]
		filename = str(filename).split('/')[-1]
		self._get_time()
		msg = self.date + " 文件: " + filename + "  行: " + str(line_) + " 函数: " + module_name + " - DEBUG : " + msg
		mess = str(Fore.BLUE + msg + Style.RESET_ALL)
		print(mess)

	def warning(self, msg):
		"""
		打印信息
		:param msg: 打印内容
		:return:
		"""
		fun_info = inspect.getframeinfo(inspect.currentframe().f_back)
		line_ = fun_info[1]
		module_name = fun_info[2]
		filename = fun_info[0]
		filename = str(filename).split('/')[-1]
		self._get_time()
		msg = self.date + " 文件: " + filename + "  行: " + str(line_) + " 函数: " + module_name + " - WARNING : " + msg
		mess = str(Fore.YELLOW + msg + Style.RESET_ALL)
		print(mess)

	def error(self, msg):
		"""
		打印信息
		:param msg: 打印内容
		:return:
		"""
		fun_info = inspect.getframeinfo(inspect.currentframe().f_back)
		line_ = fun_info[1]
		module_name = fun_info[2]
		filename = fun_info[0]
		filename = str(filename).split('/')[-1]
		self._get_time()
		msg = self.date + " 文件: " + filename + "  行: " + str(line_) + " 函数: " + module_name + " - ERROR : " + msg
		mess = str(Fore.RED + msg + Style.RESET_ALL)
		print(mess)


if __name__ == "__main__":
	log = Loger()
	log.info(msg='1')
	log.error('2')
	log.debug('3')
	log.warning('4')