13、logging模块
最简单用法
import logginglogging.warning("user [alex] attempted wrong password more than 3 times")
logging.critical("server is down")
输出
WARNING:root:user [alex] attempted wrong password more than 3 times
CRITICAL:root:server is down
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.
|
如果想把日志写到文件里,也很简单
import logginglogging.basicConfig(filename='example.log',level=logging.INFO)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
自定义日志格式
import logging
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logging.warning('is when this event was logged.')
%(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
|
用户输出的消息
|
日志同时输出到屏幕和文件
- logger提供了应用程序可以直接使用的接口;
- handler将(logger创建的)日志记录发送到合适的目的输出;
- filter提供了细度设备来决定输出哪条日志记录;
- formatter决定日志记录的最终输出格式。
他们之间的关系是这样的
每个组件的主要功能
logger
LOG=logging.getLogger(”chat.gui”)
LOG=logging.getLogger(”chat.kernel”)
Logger.setLevel(lel):指定最低的日志级别,低于lel的级别将被忽略。debug是最低的内置级别,critical为最高
Logger.addFilter(filt)、Logger.removeFilter(filt):添加或删除指定的filter
Logger.addHandler(hdlr)、Logger.removeHandler(hdlr):增加或删除指定的handler
handler
Handler.setLevel(lel):指定被处理的信息级别,低于lel级别的信息将被忽略
Handler.setFormatter():给这个handler选择一个格式
Handler.addFilter(filt)、Handler.removeFilter(filt):新增或删除一个filter对象
- logging.StreamHandler 使用这个Handler可以向类似与sys.stdout或者sys.stderr的任何文件对象(file object)输出信息。
- logging.FileHandler 和StreamHandler 类似,用于向一个文件输出日志信息。不过FileHandler会帮你打开这个文件
- 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并不会被更名,而是被删除。
- S 秒
- M 分
- H 小时
- D 天
- W 每星期(interval==0时代表星期一)
- midnight 每天凌晨
formatter 组件
fh = logging.FileHandler("access.log")
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')fh.setFormatter(formatter) #把formmater绑定到fh上
filter 组件
class IgnoreBackupLogFilter(logging.Filter):"""忽略带db backup 的日志"""def filter(self, record): #固定写法return "db backup" not in record.getMessage()
注意filter函数会返加True or False,logger根据此值决定是否输出此日志
logger.addFilter(IgnoreBackupLogFilter())
logger.debug("test ....")
logger.info("test info ....")
logger.warning("start to run db backup job ....")
logger.error("test error ....")
import loggingclass IgnoreBackupLogFilter(logging.Filter):"""忽略带db backup 的日志"""def filter(self, record): #固定写法return "db backup" not in record.getMessage()#console handler
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
#file handler
fh = logging.FileHandler('mysql.log')
#fh.setLevel(logging.WARNING)#formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
#bind formatter to ch
ch.setFormatter(formatter)
fh.setFormatter(formatter)logger = logging.getLogger("Mysql")
logger.setLevel(logging.DEBUG) #logger 优先级高于其它输出途径的#add handler to logger instance
logger.addHandler(ch)
logger.addHandler(fh)#add filter
logger.addFilter(IgnoreBackupLogFilter())logger.debug("test ....")
logger.info("test info ....")
logger.warning("start to run db backup job ....")
logger.error("test error ....")
import loggingfrom logging import handlerslogger = logging.getLogger(__name__)log_file = "timelog.log"
#fh = handlers.RotatingFileHandler(filename=log_file,maxBytes=10,backupCount=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")
logger.warning("test12")
logger.warning("test13")
logger.warning("test14")
转载于:https://www.cnblogs.com/vettel2018/p/10076272.html
13、logging模块相关推荐
- logging 模块记录日志
在日常我们写脚本调试时,对一般功能不复杂的脚本,我们一般用print函数来打印关键变量值,来判断程序是否是正常运行,但如果做教大的项 目,用这种方法就显得力不从心,所以这时候我们就要用到功能强大的lo ...
- python logging模块使用
python logging模块使用 logging模块 日志记录的重要性 在开发过程中,我们可以printf或者Debug来排查问题. 但是在生产环境中(黑盒环境)出现问题,我们并不能知道在运行的环 ...
- python 的日志logging模块学习
2019独角兽企业重金招聘Python工程师标准>>> python 的日志logging模块学习 分类: python 2011-08-02 23:51 8338人阅读 评论(0) ...
- python3 logging模块_Python3之logging模块浅析
Python3之logging模块浅析 很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误.警告等信息输出,python的logging模块提供了标准的日志接口,你可 ...
- python3 logging模块
很多程序都有记录日志的需求,并且日志包含的信息有正常的程序访问日志还可能有错误,警告等信息输出,python的logging模块提供了标准的日志接口,可以通过它存储各种格式的日志,日志级别等级:cri ...
- 常用模块之hashlib,configparser,logging模块
常用模块二 hashlib模块 hashlib提供了常见的摘要算法,如md5和sha1等等. 那么什么是摘要算法呢?摘要算法又称为哈希算法.散列算法.它通过一个函数,把任意长度的数据转换为一个长度固定 ...
- Python logging模块详解
1.简单的将日志打印到屏幕 import logginglogging.debug('This is debug message') logging.info('This is info messag ...
- 第四章: 4.1 logging模块 | 正则表达式
修改json数据然后写入json文件中 f = open('1234.json','r',encoding='utf-8') data = f.read() data1 = json.loads(da ...
- logging模块(* * * * *)
一 (简单应用). import logging logging.debug('debug message') logging.info('info message') logging.warning ...
最新文章
- (已解决)module ‘tensorflow‘ has no attribute ‘app‘
- 《精通Linux设备驱动程序开发》——1.5 Linux发行版
- 量子力学 一 基础7 酉算符与Hausdorff-Campbell公式
- Nginx内存管理详解
- 面向对象程序设计-C++ Default constructor Copy constructor Destructor Operator Overloading【第九次上课笔记】...
- 【C语言笔记初级篇】第三章:函数与递归
- mysql主动自增可以_Mysql join联表及id自增实例解析
- 基于JAVA+SpringBoot+Vue+Mybatis+MYSQL的电影在线售票系统
- 【KPC】关于为什么不用Zepto而用JQuery
- arcgis注册dsoframer.ocx等组件
- 局域网不同网段远程桌面_自动化已非原来的自动化:看虚拟局域网技术应用到罗克韦尔的DCS...
- 【工具】(七):win10常用工具整理!!!
- struts1和2的区别总结
- 解决网页pdf禁止打印的方案
- 【新手上路常见问答】关于物联网传输协议MQTT
- javascript冷门吗_冷门JS技巧
- python(十二)Uiautomator2搭建UI自动化框架实战
- 查找文件及文件内容查找
- 计算机英语单词记录1
- html css 制作网站,HTML/CSS制作网页