首页 > 编程 > Python > 正文

对python中的logger模块全面讲解

2020-02-22 23:55:07
字体:
来源:转载
供稿:网友

logging模块介绍

Python的logging模块提供了通用的日志系统,熟练使用logging模块可以方便开发者开发第三方模块或者是自己的Python应用。同样这个模块提供不同的日志级别,并可以采用不同的方式记录日志,比如文件,HTTP、GET/POST,SMTP,Socket等,甚至可以自己实现具体的日志记录方式。下文我将主要介绍如何使用文件方式记录log。

logging模块包括logger,handler,filter,formatter这四个基本概念。

logging模块与log4j的机制是一样的,只是具体的实现细节不同。模块提供logger,handler,filter,formatter。

logger:提供日志接口,供应用代码使用。logger最长用的操作有两类:配置和发送日志消息。可以通过logging.getLogger(name)获取logger对象,如果不指定name则返回root对象,多次使用相同的name调用getLogger方法返回同一个logger对象。

handler:将日志记录(log record)发送到合适的目的地(destination),比如文件,socket等。一个logger对象可以通过addHandler方法添加0到多个handler,每个handler又可以定义不同日志级别,以实现日志分级过滤显示。

filter:提供一种优雅的方式决定一个日志记录是否发送到handler。

formatter:指定日志记录输出的具体格式。formatter的构造方法需要两个参数:消息的格式字符串和日期字符串,这两个参数都是可选的。

与log4j类似,logger,handler和日志消息的调用可以有具体的日志级别(Level),只有在日志消息的级别大于logger和handler的级别。

import logginglogging.basicConfig(level=logging.DEBUG,    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',    datefmt='%a, %d %b %Y %H:%M:%S',    filename='myapp.log',    filemode='w')##################################################################################################定义一个StreamHandler,将INFO级别或更高的日志信息打印到标准错误,并将其添加到当前的日志处理对象#console = logging.StreamHandler()console.setLevel(logging.INFO)formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')console.setFormatter(formatter)logging.getLogger('').addHandler(console)#################################################################################################logging.debug('This is debug message')logging.info('This is info message')logging.warning('This is warning message') 屏幕上打印:root  : INFO  This is info messageroot  : WARNING This is warning message./myapp.log文件中内容为:Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug messageSun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info messageSun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message

logging.StreamHandler: 日志输出到流,可以是sys.stderr、sys.stdout或者文件

logging.FileHandler: 日志输出到文件

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表