python3学习-logging模块
1.logging模块的使用非常简单,引入模块就可以使用。
import logging
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
屏幕上打印:
WARNING:root:This is warning message
默认情况下,logging将日志打印到屏幕,日志级别为WARNING;
日志级别大小关系为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET,当然也可以自己定义日志级别。
2.通过logging.basicConfig函数对日志的输出格式及方式做相关配置
import logging
logging.basicConfig(filename='log.log',
format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
level=10)
logging.critical('c')
logging.fatal('f')
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
logging.info('我是一条日志信息')
log.log文件中内容为:
2017-06-21 15:53:51 PM - root - CRITICAL -demo4: c
2017-06-21 15:53:51 PM - root - CRITICAL -demo4: f
2017-06-21 15:53:51 PM - root - DEBUG -demo4: This is debug message
2017-06-21 15:53:51 PM - root - INFO -demo4: This is info message
2017-06-21 15:53:51 PM - root - WARNING -demo4: This is warning message
2017-06-21 15:53:51 PM - root - INFO -demo4: 我是一条日志信息
logging.basicConfig函数各参数:
- filename: 指定日志文件名
- filemode: 和file函数意义相同,指定日志文件的打开模式,’w’或’a’
format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示:
%(levelno)s: 打印日志级别的数值
%(levelname)s: 打印日志级别名称
%(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]
%(filename)s: 打印当前执行程序名
%(funcName)s: 打印日志的当前函数
%(lineno)d: 打印日志的当前行号
%(asctime)s: 打印日志的时间
%(thread)d: 打印线程ID
%(threadName)s: 打印线程名称
%(process)d: 打印进程ID
%(message)s: 打印日志信息datefmt: 指定时间格式,同time.strftime()
- level: 设置日志级别,默认为logging.WARNING
- stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略
3.将日志同时输出到文件和屏幕
import logging
logging.basicConfig(filename='log.log',
format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
level=10)
#定义一个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.critical('c')
logging.fatal('f')
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
logging.info('我是一条日志信息')

日志文件中同时也输出:
2017-06-21 15:59:13 PM - root - CRITICAL -demo4: c
2017-06-21 15:59:13 PM - root - CRITICAL -demo4: f
2017-06-21 15:59:13 PM - root - DEBUG -demo4: This is debug message
2017-06-21 15:59:13 PM - root - INFO -demo4: This is info message
2017-06-21 15:59:13 PM - root - WARNING -demo4: This is warning message
2017-06-21 15:59:13 PM - root - INFO -demo4: 我是一条日志信息
由上我们能看到日志的一般操作循序为:
- 创建一个流类型handler用于输出日志到控制台
- 定义handler的输出格式formatter
- 将handler添加到logging对象
4.logging日志回滚
import logging
from logging.handlers import RotatingFileHandler
#定义一个RotatingFileHandler,最多备份5个日志文件,每个日志文件最大10M
Rthandler = RotatingFileHandler('log.log', maxBytes=10*1024*1024,backupCount=5)
Rthandler.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
Rthandler.setFormatter(formatter)
logging.getLogger('').addHandler(Rthandler)
从上面两个例子来看logging有一个日志处理的主对象basicConfig,其他的都是通过addHandler的方式添加进去的。logging的集中handler方法如下:
- logging.StreamHandler: 日志输出到流,可以是sys.stderr、sys.stdout或者文件
- logging.FileHandler: 日志输出到文件
- 日志回滚方式,实际使用时用RotatingFileHandler和TimedRotatingFileHandler
- logging.handlers.BaseRotatingHandler
- logging.handlers.RotatingFileHandler
- logging.handlers.TimedRotatingFileHandler
- logging.handlers.SocketHandler: 远程输出日志到TCP/IP sockets
- logging.handlers.DatagramHandler: 远程输出日志到UDP sockets
- logging.handlers.SMTPHandler: 远程输出日志到邮件地址
- logging.handlers.SysLogHandler: 日志输出到syslog
- logging.handlers.NTEventLogHandler: 远程输出日志到Windows NT/2000/XP的事件日志
- logging.handlers.MemoryHandler: 日志输出到内存中的制定buffer
- logging.handlers.HTTPHandler: 通过"GET"或"POST"远程输出到HTTP服务器
由于StreamHandler和FileHandler是常用的日志处理方式,所以直接包含在logging模块中,而其他方式则包含在logging.handlers模块中。
5.在配置文件中配置日志信息,类似于我们在java中配置log4j的logging.config:
#logger.conf
###############################################
[loggers]
keys=root,example01,example02
[logger_root]
level=DEBUG
handlers=hand01,hand02
[logger_example01]
handlers=hand01,hand02
qualname=example01
propagate=0
[logger_example02]
handlers=hand01,hand03
qualname=example02
propagate=0
###############################################
[handlers]
keys=hand01,hand02,hand03
[handler_hand01]
class=StreamHandler
level=INFO
formatter=form02
args=(sys.stderr,)
[handler_hand02]
class=FileHandler
level=DEBUG
formatter=form01
args=('myapp.log', 'a')
[handler_hand03]
class=handlers.RotatingFileHandler
level=INFO
formatter=form02
args=('log.log', 'a', 10*1024*1024, 5)
###############################################
[formatters]
keys=form01,form02
[formatter_form01]
format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
datefmt=%a, %d %b %Y %H:%M:%S
[formatter_form02]
format=%(name)-12s: %(levelname)-8s %(message)
定义完logging.config,我们在同一个工程下的所有模块都可以使用它:
import logging
import logging.config
logging.config.fileConfig("logger.conf")
logger = logging.getLogger("example01")
logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')
注意上面配置文件中定义了多个日志对象,根据你所需要的日志级别你可以设置多个日志对象,选择调用。
python3学习-logging模块的更多相关文章
- Python3之logging模块浅析
Python3之logging模块浅析 目录 Python3之logging模块浅析 简单用法 日志与控制台同时输出 一个同时输出到屏幕.文件的完成例子 日志文件截取 日志重复打印问题解决 问题分 ...
- python3:logging模块 输出日志到文件
python自动化测试脚本运行后,想要将日志保存到某个特定文件,使用python的logging模块实现 参考代码: import logging def initLogging(logFilenam ...
- python3 之logging模块
logging.getLogger(name=None)Return a logger with the specified name or, if name is None, return a lo ...
- python3学习-Queue模块
python标准库中带有一个Queue模块,顾名思义,队列.该模块也衍生出一些基本队列不具有的功能. 我们先看一下队列的方法: put 存数据 get 取数据 empty 判断队列是否为空 qsize ...
- python3学习-lxml模块
在爬虫的学习中,我们爬取网页信息之后就是对信息项匹配,这个时候一般是使用正则.但是在使用中发现正则写的不好的时候不能精确匹配(这其实是自己的问题!)所以就找啊找.想到了可以通过标签来进行精确匹配岂不是 ...
- [python 学习] logging模块
1.将简单日志打印到屏幕: import logging logging.debug('debug message') logging.info('info message') logging.war ...
- python3学习-pickle模块
pickle提供了一个简单的持久化功能.可以将对象以文件的形式存放在磁盘上. 基本接口: pickle.dump(obj, file, [,protocol]) 注解:将对象obj保存到文件file中 ...
- Python模块学习 ---- logging 日志记录
许多应用程序中都会有日志模块,用于记录系统在运行过程中的一些关键信息,以便于对系统的运行状况进行跟踪.在.NET平台中,有非常著名的第三方开源日志组件log4net,c++中,有人们熟悉的log4cp ...
- day18 logging模块 sys shelve
昨日回顾 re 正则表达式 匹配字符串 场景 例如:爬虫,密码规则验证,邮箱地址验证,手机号码 学习re主要学习的就是 那一堆特殊符号 hashlib hash是一种算法 lib表示库 该模块包含了一 ...
随机推荐
- C语言中const的用法总结
const是一个C语言的关键字,它限定一个变量不允许被改变.使用const在一定程度上可以提高程序的安全性和可靠性,另外,在观看别人代码的时候,清晰理解const所起的作用,对理解对方的程 ...
- django基础知识之后台管理Admin站点:
Admin站点 通过使用startproject创建的项目模版中,默认Admin被启用 1.创建管理员的用户名和密码 python manage.py createsuperuser 然后按提示填写用 ...
- vmware的卸载
vmware出了点问题,在控制面板里或者是360都没法删除干净.在网上搜了点资料,找到一些删除的方法,参考链接如下: http://zhidao.baidu.com/question/30902992 ...
- 2017-10271weblogic漏洞exp测试及补丁测试
靶机:weblogic12.1.3.0 战斗机:kali 导弹:burpsuite 1.首先开启kali某端口监听 2.向靶机发送exp 3.查看kali监听 打码保平安~~ 4.打上补丁 5.验证补 ...
- HBaseCon Asia2019 会议总结
一.首先会议流程. 1. The current status of HBase 2.The advantage and technology trend of HBase on the cloud ...
- c++小游戏——彩票
#include <cstdlib> #include <iostream> #include <cstdio> #include <cmath> #i ...
- Excel催化剂开源第43波-Excel选择对象Selection在.Net开发中的使用
Excel的二次开发有一极大的优势所在,可以结合用户的交互进行程序的运行,大量用户的交互,都是从选择对象开始,用户选择了单元格区域.图形.图表等对象,之后再进行程序代码的加工处理,生成用户所需的最终结 ...
- JAVA环境+eclipse+tomcat+maven配置
1.JDK的安装 首先下载JDK,这个从sun公司官网可以下载,根据自己的系统选择64位还是32位,安装过程就是next一路到底.安装完成之后当然要配置环境变量了. ----------------- ...
- TencentTbs腾讯浏览服务 x5内核使用
Tencent TBS (下简称TBS) 腾讯浏览服务 What is it? 百度百科解释: 腾讯浏览服务(Tencent Browsing Service,以下简称TBS),由腾讯X5浏览服务升级 ...
- [PTA] 数据结构与算法题目集 6-1 单链表逆转
List Reverse(List L) { List p, q; p = L; q = L; L = NULL; while (p) { p = p->Next; q->Next = L ...