Python日志输出-logging模块使用技巧

在这里插入图片描述

本文介绍如何封装一个简单的日志配置类
  1. 自定义handler,输出到你的控制台
  2. 清晰的设置过滤等级
  3. 项目全局使用app.调用
  4. 设置自己喜欢的输出格式

编写log_setting.py

#!/usr/bin/env python
# coding=utf-8

"""
# :author: Terry Li
# :url: https://blog.csdn.net/qq_42183962
# :copyright: © 2020 Terry Li
# :motto: I believe that the God rewards the diligent.
"""
import logging


class setLog:
	def __init__(self, cmd_level=logging.DEBUG, filter_level=None, logger_name="app"):
		self.app = None
		self.logger_name = logger_name
		self.cmd_log_level = cmd_level
		self.cmd_handler = logging.StreamHandler()
		self.log_handler_global_setting()
		if filter_level:
			self.set_filter(filter_level)

	def log_handler_global_setting(self):
		"""设置StreamHandler并且添加到rootLogger中"""
		self.app = logging.getLogger(self.logger_name)
		self.app.setLevel(logging.DEBUG)

		self.cmd_handler.setLevel(logging.getLevelName(self.cmd_log_level))
		formatter = logging.Formatter(
			"%(asctime)s\t[%(filename)s-%(funcName)s]-[line:%(lineno)d]-%(levelname)s:%(message)s")
		self.cmd_handler.setFormatter(formatter)
		self.app.addHandler(self.cmd_handler)

	def set_filter(self, level):
		"""输出过滤器:控制台只输出你设置好的等级"""
		info_filter = logging.Filter()
		info_filter.filter = lambda record: record.levelno == level
		self.cmd_handler.addFilter(info_filter)

# cfg = setLog(filter_level=logging.INFO)
# app = cfg.app

if __name__ == '__main__':
	def test_print_all_log():
		"""
		1. 日志打印测试: 默认输出全部等级[debug|info|warning|error]
		"""
		log_cfg = setLog()
		test_app = log_cfg.app

		test_app.debug("debug")
		test_app.info("info")
		test_app.warning("warning")
		test_app.error("error")


	test_print_all_log()


	def test_only_print_log_of_debug_level():
		"""
		2. 日志打印测试: 设置过滤等级,使控制台只输出debug
		"""
		log_cfg = setLog(filter_level=logging.DEBUG)
		test_app = log_cfg.app

		test_app.debug("debug")
		test_app.info("info")  # 被过滤
		test_app.warning("warning")  # 被过滤
		test_app.error("error")  # 被过滤


	test_only_print_log_of_debug_level()

	""">>>>>>>项目的其他模块怎么调用?<<<<<<<<

	1.取消40、41行的注释
	2.统一用app.来调用即可,如下所示
	
	from .log_setting import app
	app.info("Hello Python!")
	"""
感谢观看,分享不易,有用请点赞~
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

木法星人

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

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

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

打赏作者

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

抵扣说明:

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

余额充值