Python 日志logging

Python 日志logging

image-20231120152320128

日志功能需要根据追踪事件的级别和严重性而定:

image-20231120152440314

Python的logging库采用模块化方法,并且提供了一些组件:

  • 记录器(Logger):提供应用程序代码直接使用的接口。
  • 处理器(Handler):将日志记录(由记录器创建)发送到适当的目的地。
  • 筛选器(Filter):提供了更细粒度的功能,用于确定要输出的日志记录。
  • 格式器(Formatter):程序在最终输出日志记录的内容格式。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import logging

LOG_FORMAT = "%(asctime)s - %(levelname)s %(name)s %(filename)s [line:%(lineno)d] - %(message)s"
logging.basicConfig(filename='log.log',format=LOG_FORMAT,level=logging.DEBUG)#设置日志级别并记录到日志文件

def print_log(name):
logging.debug('this is print_hi debug')
logging.info('this is print_hi info')
logging.warning('this is print_hi warning')
logging.error('this is print_hi error')
logging.critical('this is print_hi critical')
print(f'Hi print_hi, {name}')

if __name__ == '__main__':
print_log('zz')

LogRecord属性如下:

image-20231120153329049

Python 日志logging
http://example.com/2023/11/20/Python-log/
作者
Z Z
发布于
2023年11月20日
许可协议