使用Python内置模块实现日志功能并输出颜色

效果

系统中已内置了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')
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

坐公交也用券

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值