函数和常用模块【day06】:logging模块(八)
本节内容
1、简述
2、简单用法
3、复杂日志输出
4、handler详解
5、控制台和文件日志共同输出
一、简述
很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误,警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为debug,info,warning,error和critical 5个级别,下面我们就来看看这个日志模块logging怎么用
二、简单用法
1、简单用法
说明:日志级别有五个,分别是:debug,info,warning,error和critical,其中debug级别最低,critical级别最高,级别越低,打印的日志等级越多。
|
1
2
3
4
5
6
7
8
9
10
11
12
|
import logginglogging.debug("logging debug")logging.info("logging info")logging.warning("user [zhangqigao] attempted wrong password more than 3 times")logging.error("logging error")logging.critical("logging critical")#输出WARNING:root:user [zhangqigao] attempted wrong password more than 3 timesERROR:root:logging errorCRITICAL:root:logging critical |
注:从上面可以看出,一个模块默认的日志级别是warning
2、日志级别
看一下这几个日志级别分别代表什么意思,如表:
| Level | When it’s used |
|---|---|
DEBUG |
Detailed information, typically of interest only when diagnosing problems. |
INFO |
Confirmation that things are working as expected. |
WARNING |
An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected. |
ERROR |
Due to a more serious problem, the software has not been able to perform some function. |
CRITICAL |
A serious error, indicating that the program itself may be unable to continue running. |
3、日志写入文件
|
1
2
3
4
5
6
7
8
9
10
11
|
import logginglogging.basicConfig(filename="catalina.log",level=logging.INFO) #输入文件名,和日志级别#---日志输出---logging.debug("logging debug")logging.info("logging info")logging.warning("logging warning")#输出到文件中的内容INFO:root:logging infoWARNING:root:logging warning |
注: 这句中的level=loggin.INFO意思是,把日志纪录级别设置为INFO,也就是说,只有比日志是INFO或比INFO级别更高的日志才会被纪录到文件里,所以debug日志没有记录,如果想记录,则级别设置成debug也就是level=loggin.DEBUG
4、加入日期格式
说明:感觉上面的日志格式忘记加上时间啦,日志不知道时间怎么行呢,下面就来加上
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
logging.basicConfig(filename="catalina.log", level=logging.INFO, format='%(asctime)s %(module)s:%(levelname)s %(message)s', #格式请见第5点内容 datefmt='%m/%d/%Y %H:%M:%S %p') #需要加上format和datefmt#----日志内容-----logging.debug("logging debug")logging.info("logging info")logging.warning("logging warning")#文件输出04/11/2017 14:20:22 PM logging_mod:INFO logging info04/11/2017 14:20:22 PM logging_mod:WARNING logging warning |
5、 format的日志格式
|
%(name)s |
Logger的名字 |
|
%(levelno)s |
数字形式的日志级别 |
|
%(levelname)s |
文本形式的日志级别 |
|
%(pathname)s |
调用日志输出函数的模块的完整路径名,可能没有 |
|
%(filename)s |
调用日志输出函数的模块的文件名 |
|
%(module)s |
调用日志输出函数的模块名 |
|
%(funcName)s |
调用日志输出函数的函数名 |
|
%(lineno)d |
调用日志输出函数的语句所在的代码行 |
|
%(created)f |
当前时间,用UNIX标准的表示时间的浮 点数表示 |
|
%(relativeCreated)d |
输出日志信息时的,自Logger创建以 来的毫秒数 |
|
%(asctime)s |
字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒 |
|
%(thread)d |
线程ID。可能没有 |
|
%(threadName)s |
线程名。可能没有 |
|
%(process)d |
进程ID。可能没有 |
|
%(message)s |
用户输出的消息 |
三、复杂日志输出
之前的写法感觉要么就输入在屏幕上,要么就是输入在日志里面,那我们有没有既可以输出在日志上,又输出在日志里面呢?很明显,当然可以。下面我们就来讨论一下,如何使用复杂的日志输出。
1、简介
python使用logging模块记录日志涉及的四个主要类:
①logger:提供了应用程序可以直接使用的接口。
②handler:将(logger创建的)日志记录发送到合适的目的输出。
③filter:提供了细度设备来决定输出哪条日志记录。
④formatter:决定日志记录的最终输出格式。
2、logger
①每个程序在输出信息之前都需要获得一个logger。logger通常对应了程序的模块名,比如聊天工具的图形界面模块可以这样获得它的logger:
|
1
|
logger = logging.getLogger("chat.gui") |
核心模块可以这样写:
|
1
|
logger = logging.getLogger("chat.kernel") |
②logger.setLevel(lel)
说明:指定最低的日志级别,低于lel的级别将被忽略(debug是最低的内置级别,critical为最高)
|
1
|
logger.setLevel(logging.DEBUG) #设置级别为debug级别 |
③Logger.addFilter(filt)、Logger.removeFilter(filt)
说明:添加或删除指定的filter
④logger.addHandler(hdlr)、logger.removeHandler(hdlr)
说明:增加或删除指定的handler
|
1
2
3
|
logger.addHandler(ch)#添加handlerlogger.removeHandler(ch) #删除handler |
⑤Logger.debug()、Logger.info()、Logger.warning()、Logger.error()、Logger.critical()
说明:可以设置的日志级别
|
1
2
3
4
5
|
logger.debug('debug message')logger.info('info message')logger.warn('warn message')logger.error('error message')logger.critical('critical message') |
④获取handler个数
|
1
2
3
4
5
|
handler_len = len(logger.handlers)print(handler_len)#输出1 |
3、hander
handler对象负责发送相关的信息到指定目的地。Python的日志系统有多种Handler可以使用。有些Handler可以把信息输出到控制台,有些Logger可以把信息输出到文件,还有些 Handler可以把信息发送到网络上。如果觉得不够用,还可以编写自己的Handler。可以通过addHandler()方法添加多个多handler 。
①Handler.setLevel(lel)
说明:指定被处理的信息级别,低于lel级别的信息将被忽略。
|
1
2
|
ch = logging.StreamHandler()ch.setLevel(logging.DEBUG) |
②Handler.setFormatter()
说明:给这个handler选择一个格式
|
1
2
3
|
ch_formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") #生成格式ch.setFormatter(ch_formatter) #设置格式 |
③Handler.addFilter(filt)、Handler.removeFilter(filt)
说明:新增或删除一个filter对象
四、handler详解
1、logging.StreamHandler
说明:使用这个Handler可以向类似与sys.stdout或者sys.stderr的任何文件对象(file object)输出信息,也就是屏幕输出。
它的构造函数是:StreamHandler([strm]),其中strm参数是一个文件对象,默认是sys.stderr。
|
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
|
import logginglogger = logging.getLogger("TEST-LOG")logger.setLevel(logging.DEBUG)ch = logging.StreamHandler() #创建一个StreamHandler对象ch.setLevel(logging.DEBUG) #设置输出StreamHandler日志级别ch_formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")ch.setFormatter(ch_formatter) #设置时间格式logger.addHandler(ch)# 'application' codelogger.debug('debug message')logger.info('info message')logger.warn('warn message')logger.error('error message')logger.critical('critical message')#输出2017-04-11 16:42:49,764 - TEST-LOG - DEBUG - debug message2017-04-11 16:42:49,764 - TEST-LOG - INFO - info message2017-04-11 16:42:49,764 - TEST-LOG - WARNING - warn message2017-04-11 16:42:49,765 - TEST-LOG - ERROR - error message2017-04-11 16:42:49,765 - TEST-LOG - CRITICAL - critical message |
2、logging.FileHandler
说明:和StreamHandler类似,用于向一个文件输出日志信息,不过FileHandler会帮你打开这个文件。
它的构造函数是:FileHandler(filename[,mode])。filename是文件名,必须指定一个文件名。mode是文件的打开方式。参见Python内置函数open()的用法。默认是’a',即添加到文件末尾。
|
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
|
import logging#create logginglogger = logging.getLogger("TEST-LOG")logger.setLevel(logging.DEBUG)fh = logging.FileHandler("debug.log",encoding="utf-8") #日志输出到debug.log文件中fh.setLevel(logging.INFO) #设置FileHandler日志级别fh_formatter = logging.Formatter("%(asctime)s %(module)s:%(levelname)s %(message)s")fh.setFormatter(fh_formatter)logger.addHandler(fh)# 'application' codelogger.info('info message')logger.warn('warn message')logger.error('error message')logger.critical('critical message')#输出到文件中2017-04-11 17:09:50,035 logging_screen_output:INFO info message2017-04-11 17:09:50,035 logging_screen_output:WARNING warn message2017-04-11 17:09:50,035 logging_screen_output:ERROR error message2017-04-11 17:09:50,035 logging_screen_output:CRITICAL critical message |
3、logging.handlers.RotatingFileHandler
说明:这个Handler类似于上面的FileHandler,但是它可以管理文件大小。当文件达到一定大小之后,它会自动将当前日志文件改名,然后创建 一个新的同名日志文件继续输出。比如日志文件是chat.log。当chat.log达到指定的大小之后,RotatingFileHandler自动把 文件改名为chat.log.1。不过,如果chat.log.1已经存在,会先把chat.log.1重命名为chat.log.2。。。最后重新创建 chat.log,继续输出日志信息。
它的构造函数是:RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]]),其中filename和mode两个参数和FileHandler一样。
maxBytes用于指定日志文件的最大文件大小。如果maxBytes为0,意味着日志文件可以无限大,这时上面描述的重命名过程就不会发生。
backupCount用于指定保留的备份文件的个数。比如,如果指定为2,当上面描述的重命名过程发生时,原有的chat.log.2并不会被更名,而是被删除。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import loggingfrom logging import handlers #需要导入handlerslogger = logging.getLogger(__name__)log_file = "timelog.log"#按文件大小来分割,10个字节,保留个数是3个fh = handlers.RotatingFileHandler(filename=log_file,maxBytes=10,backupCount=3)formatter = logging.Formatter('%(asctime)s %(module)s:%(lineno)d %(message)s')fh.setFormatter(formatter)logger.addHandler(fh)logger.warning("test1")logger.warning("test12")logger.warning("test13")logger.warning("test14") |
4、logging.handlers.TimedRotatingFileHandler
说明:这个Handler和RotatingFileHandler类似,不过,它没有通过判断文件大小来决定何时重新创建日志文件,而是间隔一定时间就 自动创建新的日志文件。重命名的过程与RotatingFileHandler类似,不过新的文件不是附加数字,而是当前时间。
它的构造函数是:TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]]),其中filename参数和backupCount参数和RotatingFileHandler具有相同的意义。
interval是时间间隔。when参数是一个字符串。表示时间间隔的单位,不区分大小写。它有以下取值:①S:秒②M:分③H:小时④D:天⑤W :每星期(interval==0时代表星期一)⑥midnight:每天凌晨
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import loggingfrom logging import handlersimport timelogger = logging.getLogger(__name__)log_file = "timelog.log"#按时间来分割文件,按5秒一次分割,保留日志个数是3个fh = handlers.TimedRotatingFileHandler(filename=log_file,when="S",interval=5,backupCount=3)formatter = logging.Formatter('%(asctime)s %(module)s:%(lineno)d %(message)s')fh.setFormatter(formatter)logger.addHandler(fh)logger.warning("test1")time.sleep(2)logger.warning("test12")time.sleep(2)logger.warning("test13")time.sleep(2)logger.warning("test14")logger.warning("test15") |
五、控制台和文件日志共同输出
需要什么样的输出,只需要添加相应的handler就ok了。
1、逻辑图

2、代码如下
|
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
|
import logging#create logginglogger = logging.getLogger("TEST-LOG")logger.setLevel(logging.DEBUG)#屏幕handlerch = logging.StreamHandler()ch.setLevel(logging.DEBUG)#文件handlerfh = logging.FileHandler("debug.log",encoding="utf-8")fh.setLevel(logging.INFO)#分别创建输出日志格式ch_formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")fh_formatter = logging.Formatter("%(asctime)s %(module)s:%(levelname)s %(message)s")#设置handler的输出格式ch.setFormatter(ch_formatter)fh.setFormatter(fh_formatter)#添加handlerlogger.addHandler(ch)logger.addHandler(fh)# 'application' codelogger.debug('debug message')logger.info('info message')logger.warn('warn message')logger.error('error message')logger.critical('critical message') |
注:如果添加时间分割或者文件大小分割,再添加handler即可。添加方式请见第4节中的3、4点。
函数和常用模块【day06】:logging模块(八)的更多相关文章
- 常用模块:os模块,logging模块等
一 os模块 那么作为一个常用模块,os模块是与操作系统交互的一个模块. 那么os模块中我们常用的一般有以下几种: os.listdir('dirname') 以列表的形式列出指定目录下的所有文 ...
- os模块,sys模块,json和pickle模块,logging模块
目录 OS模块 sys模块 json和pickle模块 序列化和反序列化 json模块 pickle logging模块 OS模块 能与操作系统交互,控制文件 / 文件夹 # 创建文件夹 import ...
- 模块讲解---os模块,sys模块,json和pickle模块,logging模块
目录 模块的用法 os模块 常用的功能 sys模块 常用的功能 json和pickle模块 4. logging模块 模块的用法 通过 import 或者from......import...... ...
- Python学习日记(二十八) hashlib模块、configparse模块、logging模块
hashlib模块 主要提供字符加密算法功能,如md5.sha1.sha224.sha512.sha384等,这里的加密算法称为摘要算法.什么是摘要算法?它又称为哈希算法.散列算法,它通过一个函数把任 ...
- Python模块之hashlib模块、logging模块
一.hashlib模块 hashlib模块介绍:hashlib这个模块提供了摘要算法,例如 MD5.hsa1 摘要算法又称为哈希算法,它是通过一个函数,把任意长度的数据转换为一个长度固定的数据串,这个 ...
- python之路--day15--常用模块之logging模块
常用模块 1 logging模块 日志级别:Noset (不设置) Debug---(调试信息)----也可用10表示 Info--(消息信息)----也可用20表示 Warning---(警告信息) ...
- 《Python》hashlib模块、configparser模块、logging模块
一.hashlib模块 Python的hashlib模块中提供了常见的摘要算法,如md5,sha1等等. 摘要算法又称哈希算法.散列算法.它通过一个函数,把任意长度的数据转换为一个长度固定的字符串(通 ...
- 模块二 hashlib模块、configparser模块、logging模块
算法介绍 Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等. 什么是摘要算法呢?摘要算法又称哈希算法.散列算法.它通过一个函数,把任意长度的数据转换为一个长度固定的数据串(通常 ...
- subprocess模块和logging模块
主要内容: 一.subprocess模块 二.logging模块 1️⃣ subprocess模块 三种执行命令的方法 subprocess.run(*popenargs, input=None, ...
- 模块之 logging模块 time 模块 random模块 sys模块 pickle模块
1.如果执行文件不在项目根目录下,需要添加项目根目录到sys.path中2.调用业务逻辑 2.logging模块 程序日志是 什么时间发生了什么事情,以及当时的情况 不是logging的话 记录日志的 ...
随机推荐
- SSRS配置1:凭证和邮件
SSRS是微软的高度集成的报表服务,通过报表服务配置管理器(Reporting Service Configuration Manager,简称RSCM),能够轻松实现报表的配置和管理,本文主要分享凭 ...
- 设计模式 笔记 迭代器模式 Iterator
//---------------------------15/04/26---------------------------- //Iterator 迭代器模式----对象行为型模式 /* 1:意 ...
- Spring+SpringMVC+MyBatis整合基础篇(二)牛刀小试
前言 承接上文,该篇即为项目整合的介绍了. 废话不多说,先把源码和项目地址放上来,重点要写在前面. 项目展示地址,点这里http://ssm-demo.13blog.site,账号:admin 密码: ...
- MVC5.0知识点梳理
我们在使用MVC的时候或许总是在使用着自己一直熟悉的知识点去实现已有的功能,多梳理一些知识点让每种功能的实现方式可以多样化. 我们在开发小型系统时总是使用微软MVC的脚手架功能,比如路由可能就是使用了 ...
- spring boot 2.0 源码分析(二)
在上一章学习了spring boot 2.0启动的大概流程以后,今天我们来深挖一下SpringApplication实例变量的run函数. 先把这段run函数的代码贴出来: /** * Run the ...
- Python与rrdtool的结合模块
rrdtool(round robin database)工具为环状数据库的存储格式,round robin是一种处理定量数据以及当前元素指针的技术.rrdtool主要用来跟踪对象的变化情况,生成这些 ...
- 作业要求20160901 从edu.cnblogs.com中抄过来的,备忘
[已完成] 杨贵福 发布于 2016-09-01 21:51 开通技术博客,博客园 cnblogs 关注 杨贵福 younggift,回贴 "构建之法东北师大站,继续 2016秋" ...
- one team
Double H Team 1.队员 王熙航211606379(队长) 李冠锐211606364 曾磊鑫211606350 戴俊涵211606359 聂寒冰211606324 杨艺勇211606342 ...
- Linux内核分析第五章读书笔记
第五章 系统调用 在操作系统中,内核提供了用户进程与内核进行交互的一组接口,这些接口在应用程序和内核之间扮演了使者的角色,保证系统稳定可靠,避免应用程序肆意妄行. 5.1 与内核通信 系统调用在用户空 ...
- 编码用命令行执行的C语言词语统计程序
需求介绍 程序处理用户需求的模式为: wc.exe [parameter][filename] 在[parameter]中,用户通过输入参数与程序交互,需实现的功能如下: 1.基本功能 支持 -c ...