logging模块
log日志级别主要有DEBUG,INFO,WARNING,ERROR,CRITICAL,日志级别是逐渐增加的。
"简单用法"#!/usr/bin/env python# -*- coding:utf-8 -*-# Author: vitaimport logginglogging.warning("warning message!")logging.critical("critical message!")E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.pyWARNING:root:warning message!CRITICAL:root:critical message!Process finished with exit code 0
"level=logging.INFO意思是把日志级别设置为info,即只有比日志info级别更高的日志才会记录到文件中,在这个例子中,debug级别的日志是不会被记录的,如果想要记录debug的日志,需要设置为lvel=logging.DEBUG""把日志写到文件中"#!/usr/bin/env python# -*- coding:utf-8 -*-# Author: vitaimport logginglogging.basicConfig(filename='example.log',level=logging.INFO)logging.debug("debug message!")logging.info("info message!")logging.warning("warning message!")logging.critical("critical message!")E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.pyProcess finished with exit code 0查看文件内容INFO:root:info message!WARNING:root:warning message!CRITICAL:root:critical message!
2.自定义日志格式
#!/usr/bin/env python# -*- coding:utf-8 -*-# Author: vitaimport logginglogging.basicConfig(filename='example.log',level=logging.INFO,format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')logging.debug("debug message!")logging.info("info message!")logging.warning("warning message!")logging.critical("critical message!")E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.pyProcess finished with exit code 0查看日志05/06/2019 06:48:18 PM info message!05/06/2019 06:48:18 PM warning message!05/06/2019 06:48:18 PM critical message!
"还可以自定义其他格式"%(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 用户输出的消息
#!/usr/bin/env python# -*- coding:utf-8 -*-# Author: vitaimport logginglogging.basicConfig(format='%(process)d %(threadName)s %(thread)d %(relativeCreated)d %(created)f %(lineno)d %(funcName)s %(module)s %(filename)s %(levelname)s %(levelno)s %(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')logging.debug("debug message!")logging.info("info message!")logging.warning("warning message!")logging.critical("critical message!")E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py6892 MainThread 13956 0 1557140166.898770 8 <module> test test.py WARNING 30 05/06/2019 06:56:06 PM warning message!6892 MainThread 13956 0 1557140166.898770 9 <module> test test.py CRITICAL 50 05/06/2019 06:56:06 PM critical message!Process finished with exit code 0
3.日志同时输出到屏幕和文件
logger提供了应用程序可以直接使用的接口;handler将(logger创建的)日志记录发送到合适的目的输出;filter提供了细度设备来决定输出哪条日志记录;formatter决定日志记录的最终输出格式
每个程序在输出信息之前都需要获得一个logger对象。logger通常对应着模块名,同时也是生成的日志文件的文件名Logger=logging.getLogger("modulename")还可以为他绑定handler和filterLogger.setLevel(lel):指定最低的日志级别,低于lel的级别将被忽略。debug是最低的内置级别,critical为最高Logger.addFilter(filt)、Logger.removeFilter(filt):添加或删除指定的filterLogger.addHandler(hdlr)、Logger.removeHandler(hdlr):增加或删除指定的handlerLogger.debug()、Logger.info()、Logger.warning()、Logger.error()、Logger.critical():可以用于输出相应级别的日志
3.2handler
handler对象负责发送相关的信息到指定目的地。Python的日志系统有多种Handler可以使用。StreamHandler可以把日志信息输出到控制台,FileHandler可以把日志信息输出到文件中,可以通过addHandler()为logger对象添加多个handler
Handler.setLevel(lel):指定被处理的信息级别,低于lel级别的信息将被忽略Handler.setFormatter():给这个handler选择一个格式Handler.addFilter(filt)、Handler.removeFilter(filt):新增或删除一个filter对象
3.2.1常用的Handler
1.logging.StreamHandler
使用这个Handler可以向类似与sys.stdout或者sys.stderr的任何文件对象(file object)输出信息。
2.logging.FileHandler
和StreamHandler 类似,用于向一个文件输出日志信息。不过FileHandler会帮你打开这个文件
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并不会被更名,而是被删除。
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 每天凌晨
3.3formatter
日志的formatter是个独立的组件,可以跟handler组合fh = logging.FileHandler("access.log")formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')fh.setFormatter(formatter) #把formmater绑定到fh上
3.4filter
自定义filterclass IgnoreBackupLogFilter(logging.Filter): """忽略带db backup 的日志""" def filter(self, record): #固定写法 return "db backup" not in record.getMessage()注意filter函数会返加True or False,logger根据此值决定是否输出此日志然后把这个filter添加到logger中logger.addFilter(IgnoreBackupLogFilter())下面的日志就会把符合filter条件的过滤掉logger.debug("test ....")logger.info("test info ....")logger.warning("start to run db backup job ....")logger.error("test error ....")
3.5一个同时输出到屏幕、文件、带filter的完整例子
#!/usr/bin/env python# -*- coding:utf-8 -*-# Author: vitaimport loggingclass IgnoreBackupLogFilter(logging.Filter): """忽略带db backup 的日志""" def filter(self, record): #固定写法 return "db backup" not in record.getMessage()#console handlerch = logging.StreamHandler()ch.setLevel(logging.INFO)#file handlerfh = logging.FileHandler('mysql.log')fh.setLevel(logging.WARNING)#formatterformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')#bind formatter to chch.setFormatter(formatter)fh.setFormatter(formatter)logger = logging.getLogger("Mysql")logger.setLevel(logging.DEBUG) #logger 优先级高于其它输出途径的,这里是全局的日志级别设置,默认是warning级别#add handler to logger instancelogger.addHandler(ch)logger.addHandler(fh)#add filterlogger.addFilter(IgnoreBackupLogFilter())logger.debug("test ....")logger.info("test info ....")logger.warning("start to run db backup job ....")logger.warning("warning ....")logger.error("test error ....")控制台的日志E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py2019-05-06 19:48:24,999 - Mysql - INFO - test info ....2019-05-06 19:48:24,999 - Mysql - WARNING - warning ....2019-05-06 19:48:25,000 - Mysql - ERROR - test error ....Process finished with exit code 0mysql.log文件中内容2019-05-06 19:47:49,338 - Mysql - ERROR - test error ....2019-05-06 19:48:24,999 - Mysql - WARNING - warning ....2019-05-06 19:48:25,000 - Mysql - ERROR - test error ...."其中有三处设置了日志级别,最先对日志进行过滤的是logger.setLevel(logging.DEBUG) ,然后剩下的日志,分别由handler的日志级别对日志进行过滤,只有级别高于设置的level的日志才能输出"
3.6文件自动截断的例子
#!/usr/bin/env python# -*- coding:utf-8 -*-# Author: vitaimport loggingimport 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=2,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")E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.pyProcess finished with exit code 0
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。