• 一个简单使用logging的例子


    1.logging基本使用

    先配置logging,然后使用logging输出不同level的信息(就不用先print输出,调试好了再注释掉)

    import logging
    logging.basicConfig(level=logging.INFO #设置日志输出格式
                        # ,filename="demo.log" #log日志输出的文件位置和文件名
                        # ,filemode="w" #文件的写入格式,w为重新写入文件,默认是追加
                        ,format="%(asctime)s - %(name)s - %(levelname)-8s - %(filename)-8s : %(lineno)s line - %(message)s" #日志输出的格式, -8表示占位符,让输出左对齐,输出长度都为8位
                        ,datefmt="%Y-%m-%d %H:%M:%S" #时间输出的格式
                        )
    
    class Calc(object):
    	"""
    	calc x // y
    	"""
    	def __init__(self, x=0, y=0):
    		self._x = x
    		self._y = y
    		logging.debug("init x=%d, y=%d" % (self._x, self._y))
    	
    	@property
    	def x(self):
    		return self._x 
    	@x.setter
    	def x(self, x):
    		self._x = x
    		logging.debug("set x=%d", self._x)
    	
    	@property
    	def y(self):
    		return self._y
    	@y.setter
    	def y(self, y):
    		logging.warning("notice: y can not be zero")
    		self._y = y
    		logging.debug("set y=%d", self._y)
    
    	def calc(self):
    		if self._x < self._y:
    			logging.warning("x is less than y")
    		logging.info("calc: x=%d, y=%d", self._x, self._y)
    		
    		try:
    			return self._x // self._y
    		except:
    			logging.error("y is zero")
    			raise ValueError("y can not be zero")
    		finally:
    			print("over")
    
    c = Calc()
    c.x = 10
    c.y = 20
    # c.y = 0
    c.calc()
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53

    2.logging自定义使用

    logging采用模块化设计,主要包含四个部分:

    • logger:类似于笔,产生日志
    • handler:日志输出到哪里?控制台还是文件?
    • filter:
    • formatter:

    依次配置各个部分,具体见注释

    import logging
    
    class Calc(object):
    	"""
    	calc x // y
    	"""
    	def __init__(self, x=0, y=0):
    		self.log()
    		self._x = x
    		self._y = y
    		self.logger.debug("init x=%d, y=%d" % (self._x, self._y))
    	
    	@property
    	def x(self):
    		return self._x 
    	@x.setter
    	def x(self, x):
    		self._x = x
    		self.logger.debug("set x=%d", self._x)
    	
    	@property
    	def y(self):
    		return self._y
    	@y.setter
    	def y(self, y):
    		self.logger.warning("notice: y can not be zero")
    		self._y = y
    		self.logger.debug("set y=%d", self._y)
    
    	def log(self):
    		# 创建logger并设置level(最好是DEBUG),单例模式,相同名字的logger只能创建一个
    		self.logger = logging.getLogger("logger")
    		self.logger.setLevel(level=logging.DEBUG)
    
    		# 将日志输出到哪里,屏幕和文件,handler的level应该不低于logger
    		# 详细日志输出到文件,简略日志输出到屏幕
    		self.handler_stream = logging.StreamHandler()
    		self.handler_stream.setLevel(level=logging.WARNING)
    		self.handler_file = logging.FileHandler('logger.log', mode='w')
    		self.handler_file.setLevel(level=logging.DEBUG)
    
    		# 设置输出格式
    		self.formatter = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)-8s - %(filename)-8s : line %(lineno)s  - %(message)s",
    					datefmt="%Y-%m-%d %H:%M:%S")
    		
    		# handler设置输出格式,绑定formatter
    		self.handler_file.setFormatter(self.formatter)
    		self.handler_stream.setFormatter(self.formatter)
    
    		# logger设置输出位置,一个logger可以绑定多个handler
    		self.logger.addHandler(self.handler_stream)
    		self.logger.addHandler(self.handler_file)
    
    		# 只允许logger1,相当于不输出logger的日志
    		self.filter = logging.Filter("logger1")
    		self.logger.addFilter(self.filter)
    		# self.handler_stream.addFilter(self.filter)
    
    	def calc(self):
    		if self._x < self._y:
    			self.logger.warning("x is less than y")
    		self.logger.info("calc: x=%d, y=%d", self._x, self._y)
    		
    		try:
    			return self._x // self._y
    		except:
    			self.logger.error("y is zero", exc_info=True)
    			raise ValueError("y can not be zero")
    		finally:
    			print("over")
    
    c = Calc()
    c.x = 10
    c.y = 20
    # c.y = 0
    c.calc()
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77

    可以将关于日志的配置放到配置文件中,从而更灵活,配置文件可以是conf文件、yaml文件、JSON文件、INI文件等,由于自己不写大型项目,这部分暂且略过。

     
     

    参考资料

    logging – Python的日志记录工具
    Python Logging系列blog
    Python中logging模块的基本使用(日志模块)
    最棒总结!Python日志库 logging 使用指南来了
    python日志:logging模块使用
    python logging模块使用教程
    Python之日志处理(logging模块)
    Python实用教程系列——Logging日志模块

  • 相关阅读:
    金蝶云星空BOS设计器中基础资料字段属性“过滤”设置获取当前界面的基础资料值作为查询条件
    ElasticSearch - DSL查询文档语法,以及深度分页问题、解决方案
    Toronto Research Chemicals 杀菌抗生素丨磷霉素-蔗糖醚二钠盐
    泛型编程与模板
    [Node]几个常用的node后端框架
    【Java SE】汉诺塔问题
    华为OD机试 - 机器人搬砖(Java & JS & Python & C)
    【Android 】android13 新权限获取 读写文件权限
    基于SpringBoot+Vue+uniapp的考试系统的详细设计和实现(源码+lw+部署文档+讲解等)
    系统性能优化总结
  • 原文地址:https://blog.csdn.net/weixin_44343319/article/details/126393441