日志记录功能

日志记录器Logger
记录日志信息的唯一对象,根据不同的信息等级使用不同的记录方法
x.debug() 记录调试信息,logging.DEBUG(10)
x.info() 记录普通信息,loggjing.INFO(20)
x.warning() 记录警告信息, logging.WARNING(30)
x.error() 记录错误的信息, logging.ERROR(40)
x.critical() 记录严重错误的信息,logging.CRITICAL(50)
创建或获取记录器:logging.getLogger(name) 如果name为空,则默认为root.
记录器可以添加处理器和过滤器:x.addHandler(Handler())、 x.addFilter(Filter())
日志处理器 Handler
作用:将记录器的相关日志信息,进行特定业务的处理,如写入文件的FileHandler、 发送邮件的 SMTPHandler、上传远程服务器的HTTPHandler等。
【注意】 处理器可以设置日志格式化 Formatter: h.setFormatter(Formatter())

日志格式化 Formatter
作用:将记录日志信息进行格式化 (可以选择重要的信息、或者自定义格式的信息)
日志的格式:

     |  %(name)s            Name of the logger (logging channel)
     |  %(levelno)s         Numeric logging level for the message (DEBUG, INFO,
     |                      			  WARNING, ERROR, CRITICAL)
     |  %(levelname)s       Text logging level for the message ("DEBUG", "INFO",
     |       					               "WARNING", "ERROR", "CRITICAL")
     |  %(pathname)s        Full pathname of the source file where the logging
     |  				                       call was issued (if available)
     |  %(filename)s        Filename portion of pathname
     |  %(module)s          Module (name portion of filename)
     |  %(lineno)d            Source line number where the logging call was issued
     |         					             (if available)
     |  %(funcName)s        Function name
     |  %(created)f    	     Time when the LogRecord was created (time.time()
     |         					             return value)
     |  %(asctime)s         Textual time when the LogRecord was created
     |  %(msecs)d            Millisecond portion of the creation time
     |  %(relativeCreated)d Time in milliseconds when the LogRecord was created,
     |                   						   relative to the time the logging module was loaded
     |                 						     (typically at application startup time)
     |  %(thread)d          Thread ID (if available)
     |  %(threadName)s      Thread name (if available)
     |  %(process)d     		    Process ID (if available)
     |  %(message)s      	   The result of record.getMessage(), computed just as
     |               					       the record is emitted
     |  

经典的日志格式:

```python
[ %(asctime)s - %(levelname)s <  line %(lineno)s at %(pathname)s >  ] %(messages)s
```
如果给定的日志格式中变量不能完成业务需求时,可以自定义:
```python
[ %(asctime)s - % (username)s :(ip)s < %(action)s >  ] %(messages)s
```
以上usernmae、ip和action都属于自定义的格式变量,在记录器记录信息时指定extra参数,它是一个字典类型,key即为扩展的变量名,value即是它的值。

日志的过滤器 Filter
作用:过滤一些敏感的记录日志信息。

日志的应用

import logging
from logging import StreamHandler,FilrHandler,Formatter,Filter

class MsgFilter(Filter):
	def filter(self, record):
	// print(dir(record))
	return recorf.msg.find('休息') == -1
	// return true

logger = logging.getLogger('middleware')
# 设置记录器的等级:  DEBUG --> INFO --> WARNING -->  ERROR -->CRITICAL
logger.setLevel(logging.INFO)		# 记录器可以记录INFO及以上等级的信息

# 添加日志过滤器
logging.addFilter(MsgFilter())

# 创建日志处理器
handler1 = StreamHandler()	# 流处理器,标准输出
hanfler1.setLevel(logging.INFO)
handler1.setFormatter(Formatter(
		fmt = '[ %(asctime)s - %(levelname)s  ] %(message)s',
		datefmt = '%Y-%m-%d %H:%M:%S'
))

# 向记录器添加处理器
logger.addHandler(handler1)

handler2 = FileHandler('error.log',encoding = 'utf-8')
handler2.setLevel(logging.ERROR)
handler2.setFormatter(Formatter(
		fmt = "[ %(asctime)s - %(levelname)s < line %(lineno)s at %(pathname)s > ] %(message)s",
		datefmt = '%Y-%m-%d %H:%M:%S'
))
logger.addHandler(handler2)


if __name__ == '__main__'
	// x = logging.getLogger('middleware')	# 获取middleware的记录器
	// x.debug('小狄最帅')
	// x.info('duck')
	// x.warning('tom')
	// x.error('早点下课')
	// x.critical('早点休息')
	logging.getLogger('middleware'). debug('tom最帅')
	logging.getLogger('middleware'). info('duck最帅')
	logging.getLogger('middleware'). warning('jack最帅')
	logging.getLogger('middleware').error('早点下课')
	logging.getLogger('middleware'). critical('早点休息')

扩展自定义格式化字段

mylogger = logging.getLogger('sys_action')
mylogger.setLevel(logging.INFO)

myhandler = StreamHandler()
myhandler.setLevel(logging.INFO)
myhandler.setFormatter(Formtter(
	fmt="[ %(asctime)s - %(username)s: %(ip)s < %(action)s > ] %(message)s",
    datefmt='%Y-%m-%d %H:%M:%S'
))

mylogger.addHandler(myhandler)

if __name__ = '__main__':
extra_info = {
	'username' : 'admin',
	'ip' : '10.36.172.110',
	'action' : 'del category'
}

logging.getLogger('sys_action').debug('tom最帅', extra=extra_info)
logging.getLogger('sys_action').info('disen最帅', extra=extra_info)
logging.getLogger('sys_action').warning('jack最帅',extra=extra_info)
logging.getLogger('sys_action').error('早点下课', extra=extra_info)
logging.getLogger('sys_action').critical('早点休息', extra=extra_info)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值