(转)python logging模块
1 logging模块简介
logging模块是python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级、日志保存路径、日志文件回滚等;相比print,具备如下优点:
- 可以通过设置不同的日志等级,在release版本中只输出重要信息,而不必显示大量的调试信息;
- print将所有信息都输出到标准输出中,严重影响开发者从标准输出中查看其它数据;logging则可以由开发者决定将信息输出到什么地方,以及怎么输出;
2 logging模块使用
2.1 基本使用
配置logging基本的设置,然后在控制台输出日志,
import logging logging.basicconfig(level = logging.info,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getlogger(__name__) logger.info("start print log") logger.debug("do something") logger.warning("something maybe fail.") logger.info("finish")
运行时,控制台输出,
2016-10-09 19:11:19,434 - __main__ - info - start print log 2016-10-09 19:11:19,434 - __main__ - warning - something maybe fail. 2016-10-09 19:11:19,434 - __main__ - info - finish
logging中可以选择很多消息级别,如debug、info、warning、error以及critical。通过赋予logger或者handler不同的级别,开发者就可以只输出错误信息到特定的记录文件,或者在调试时只记录调试信息。
例如,我们将logger的级别改为debug,再观察一下输出结果,
logging.basicconfig(level = logging.debug,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
控制台输出,可以发现,输出了debug的信息。
2016-10-09 19:12:08,289 - __main__ - info - start print log 2016-10-09 19:12:08,289 - __main__ - debug - do something 2016-10-09 19:12:08,289 - __main__ - warning - something maybe fail. 2016-10-09 19:12:08,289 - __main__ - info - finish
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.warnning;
stream:指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略;
2.2 将日志写入到文件
2.2.1 将日志写入到文件
设置logging,创建一个filehandler,并对输出消息的格式进行设置,将其添加到logger,然后将日志写入到指定的文件中,
import logging logger = logging.getlogger(__name__) logger.setlevel(level = logging.info) handler = logging.filehandler("log.txt") handler.setlevel(logging.info) formatter = logging.formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setformatter(formatter) logger.addhandler(handler) logger.info("start print log") logger.debug("do something") logger.warning("something maybe fail.") logger.info("finish")
log.txt中日志数据为,
2016-10-09 19:01:13,263 - __main__ - info - start print log 2016-10-09 19:01:13,263 - __main__ - warning - something maybe fail. 2016-10-09 19:01:13,263 - __main__ - info - finish
2.2.2 将日志同时输出到屏幕和日志文件
logger中添加streamhandler,可以将日志输出到屏幕上,
import logging logger = logging.getlogger(__name__) logger.setlevel(level = logging.info) handler = logging.filehandler("log.txt") handler.setlevel(logging.info) formatter = logging.formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setformatter(formatter) console = logging.streamhandler() console.setlevel(logging.info) logger.addhandler(handler) logger.addhandler(console) logger.info("start print log") logger.debug("do something") logger.warning("something maybe fail.") logger.info("finish")
可以在log.txt文件和控制台中看到,
2016-10-09 19:20:46,553 - __main__ - info - start print log 2016-10-09 19:20:46,553 - __main__ - warning - something maybe fail. 2016-10-09 19:20:46,553 - __main__ - info - finish
可以发现,logging有一个日志处理的主对象,其他处理方式都是通过addhandler添加进去,logging中包含的handler主要有如下几种,
handler名称:位置;作用 streamhandler:logging.streamhandler;日志输出到流,可以是sys.stderr,sys.stdout或者文件 filehandler:logging.filehandler;日志输出到文件 baserotatinghandler:logging.handlers.baserotatinghandler;基本的日志回滚方式 rotatinghandler:logging.handlers.rotatinghandler;日志回滚方式,支持日志文件最大数量和日志文件回滚 timerotatinghandler:logging.handlers.timerotatinghandler;日志回滚方式,在一定时间区域内回滚日志文件 sockethandler:logging.handlers.sockethandler;远程输出日志到tcp/ip sockets datagramhandler:logging.handlers.datagramhandler;远程输出日志到udp sockets smtphandler:logging.handlers.smtphandler;远程输出日志到邮件地址 sysloghandler:logging.handlers.sysloghandler;日志输出到syslog nteventloghandler:logging.handlers.nteventloghandler;远程输出日志到windows nt/2000/xp的事件日志 memoryhandler:logging.handlers.memoryhandler;日志输出到内存中的指定buffer httphandler:logging.handlers.httphandler;通过"get"或者"post"远程输出到http服务器
2.2.3 日志回滚
使用rotatingfilehandler,可以实现日志回滚,
import logging from logging.handlers import rotatingfilehandler logger = logging.getlogger(__name__) logger.setlevel(level = logging.info) #定义一个rotatingfilehandler,最多备份3个日志文件,每个日志文件最大1k rhandler = rotatingfilehandler("log.txt",maxbytes = 1*1024,backupcount = 3) rhandler.setlevel(logging.info) formatter = logging.formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') rhandler.setformatter(formatter) console = logging.streamhandler() console.setlevel(logging.info) console.setformatter(formatter) logger.addhandler(rhandler) logger.addhandler(console) logger.info("start print log") logger.debug("do something") logger.warning("something maybe fail.") logger.info("finish")
可以在工程目录中看到,备份的日志文件,
2016/10/09 19:36 732 log.txt 2016/10/09 19:36 967 log.txt.1 2016/10/09 19:36 985 log.txt.2 2016/10/09 19:36 976 log.txt.3
2.3 设置消息的等级
可以设置不同的日志等级,用于控制日志的输出,
日志等级:使用范围 fatal:致命错误 critical:特别糟糕的事情,如内存耗尽、磁盘空间为空,一般很少使用 error:发生错误时,如io操作失败或者连接问题 warning:发生很重要的事件,但是并不是错误时,如用户登录密码错误 info:处理请求或者状态变化等日常事务 debug:调试过程中使用debug等级,如算法中每个循环的中间状态
2.4 捕获traceback
python中的traceback模块被用于跟踪异常返回信息,可以在logging中记录下traceback,
代码,
import logging logger = logging.getlogger(__name__) logger.setlevel(level = logging.info) handler = logging.filehandler("log.txt") handler.setlevel(logging.info) formatter = logging.formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setformatter(formatter) console = logging.streamhandler() console.setlevel(logging.info) logger.addhandler(handler) logger.addhandler(console) logger.info("start print log") logger.debug("do something") logger.warning("something maybe fail.") try: open("sklearn.txt","rb") except (systemexit,keyboardinterrupt): raise except exception: logger.error("faild to open sklearn.txt from logger.error",exc_info = true) logger.info("finish")
控制台和日志文件log.txt中输出,
start print log something maybe fail. faild to open sklearn.txt from logger.error traceback (most recent call last): file "g:\zhb7627\code\eclipse workspace\pythontest\test.py", line 23, in <module> open("sklearn.txt","rb") ioerror: [errno 2] no such file or directory: 'sklearn.txt' finish
也可以使用logger.exception(msg,_args),它等价于logger.error(msg,exc_info = true,_args),
将
logger.error("faild to open sklearn.txt from logger.error",exc_info = true)
替换为,
logger.exception("failed to open sklearn.txt from logger.exception")
控制台和日志文件log.txt中输出,
start print log something maybe fail. failed to open sklearn.txt from logger.exception traceback (most recent call last): file "g:\zhb7627\code\eclipse workspace\pythontest\test.py", line 23, in <module> open("sklearn.txt","rb") ioerror: [errno 2] no such file or directory: 'sklearn.txt' finish
2.5 多模块使用logging
主模块mainmodule.py,
import logging import submodule logger = logging.getlogger("mainmodule") logger.setlevel(level = logging.info) handler = logging.filehandler("log.txt") handler.setlevel(logging.info) formatter = logging.formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setformatter(formatter) console = logging.streamhandler() console.setlevel(logging.info) console.setformatter(formatter) logger.addhandler(handler) logger.addhandler(console) logger.info("creating an instance of submodule.submoduleclass") a = submodule.submoduleclass() logger.info("calling submodule.submoduleclass.dosomething") a.dosomething() logger.info("done with submodule.submoduleclass.dosomething") logger.info("calling submodule.some_function") submodule.som_function() logger.info("done with submodule.some_function")
子模块submodule.py,
import logging module_logger = logging.getlogger("mainmodule.sub") class submoduleclass(object): def __init__(self): self.logger = logging.getlogger("mainmodule.sub.module") self.logger.info("creating an instance in submoduleclass") def dosomething(self): self.logger.info("do something in submodule") a = [] a.append(1) self.logger.debug("list a = " + str(a)) self.logger.info("finish something in submoduleclass") def som_function(): module_logger.info("call function some_function")
执行之后,在控制和日志文件log.txt中输出,
2016-10-09 20:25:42,276 - mainmodule - info - creating an instance of submodule.submoduleclass 2016-10-09 20:25:42,279 - mainmodule.sub.module - info - creating an instance in submoduleclass 2016-10-09 20:25:42,279 - mainmodule - info - calling submodule.submoduleclass.dosomething 2016-10-09 20:25:42,279 - mainmodule.sub.module - info - do something in submodule 2016-10-09 20:25:42,279 - mainmodule.sub.module - info - finish something in submoduleclass 2016-10-09 20:25:42,279 - mainmodule - info - done with submodule.submoduleclass.dosomething 2016-10-09 20:25:42,279 - mainmodule - info - calling submodule.some_function 2016-10-09 20:25:42,279 - mainmodule.sub - info - call function some_function 2016-10-09 20:25:42,279 - mainmodule - info - done with submodule.some_function
首先在主模块定义了logger'mainmodule',并对它进行了配置,就可以在解释器进程里面的其他地方通过getlogger('mainmodule')得到的对象都是一样的,不需要重新配置,可以直接使用。定义的该logger的子logger,都可以共享父logger的定义和配置,所谓的父子logger是通过命名来识别,任意以'mainmodule'开头的logger都是它的子logger,例如'mainmodule.sub'。
实际开发一个application,首先可以通过logging配置文件编写好这个application所对应的配置,可以生成一个根logger,如'pythonapp',然后在主函数中通过fileconfig加载logging配置,接着在application的其他地方、不同的模块中,可以使用根logger的子logger,如'pythonapp.core','pythonapp.web'来进行log,而不需要反复的定义和配置各个模块的logger。
3 通过json或者yaml文件配置logging模块
尽管可以在python代码中配置logging,但是这样并不够灵活,最好的方法是使用一个配置文件来配置。在python 2.7及以后的版本中,可以从字典中加载logging配置,也就意味着可以通过json或者yaml文件加载日志的配置。
3.1 通过json文件配置
json配置文件,
{ "version":1, "disable_existing_loggers":false, "formatters":{ "simple":{ "format":"%(asctime)s - %(name)s - %(levelname)s - %(message)s" } }, "handlers":{ "console":{ "class":"logging.streamhandler", "level":"debug", "formatter":"simple", "stream":"ext://sys.stdout" }, "info_file_handler":{ "class":"logging.handlers.rotatingfilehandler", "level":"info", "formatter":"simple", "filename":"info.log", "maxbytes":"10485760", "backupcount":20, "encoding":"utf8" }, "error_file_handler":{ "class":"logging.handlers.rotatingfilehandler", "level":"error", "formatter":"simple", "filename":"errors.log", "maxbytes":10485760, "backupcount":20, "encoding":"utf8" } }, "loggers":{ "my_module":{ "level":"error", "handlers":["info_file_handler"], "propagate":"no" } }, "root":{ "level":"info", "handlers":["console","info_file_handler","error_file_handler"] } }
通过json加载配置文件,然后通过logging.dictconfig配置logging,
import json import logging.config import os def setup_logging(default_path = "logging.json",default_level = logging.info,env_key = "log_cfg"): path = default_path value = os.getenv(env_key,none) if value: path = value if os.path.exists(path): with open(path,"r") as f: config = json.load(f) logging.config.dictconfig(config) else: logging.basicconfig(level = default_level) def func(): logging.info("start func") logging.info("exec func") logging.info("end func") if __name__ == "__main__": setup_logging(default_path = "logging.json") func()
3.2 通过yaml文件配置
通过yaml文件进行配置,比json看起来更加简介明了,
version: 1 disable_existing_loggers: false formatters: simple: format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s" handlers: console: class: logging.streamhandler level: debug formatter: simple stream: ext://sys.stdout info_file_handler: class: logging.handlers.rotatingfilehandler level: info formatter: simple filename: info.log maxbytes: 10485760 backupcount: 20 encoding: utf8 error_file_handler: class: logging.handlers.rotatingfilehandler level: error formatter: simple filename: errors.log maxbytes: 10485760 backupcount: 20 encoding: utf8 loggers: my_module: level: error handlers: [info_file_handler] propagate: no root: level: info handlers: [console,info_file_handler,error_file_handler]
通过yaml加载配置文件,然后通过logging.dictconfig配置logging,
import yaml import logging.config import os def setup_logging(default_path = "logging.yaml",default_level = logging.info,env_key = "log_cfg"): path = default_path value = os.getenv(env_key,none) if value: path = value if os.path.exists(path): with open(path,"r") as f: config = yaml.load(f) logging.config.dictconfig(config) else: logging.basicconfig(level = default_level) def func(): logging.info("start func") logging.info("exec func") logging.info("end func") if __name__ == "__main__": setup_logging(default_path = "logging.yaml") func()
4 reference
推荐阅读
-
从零开始的Python学习Episode 13——常用模块
-
python创建DataFrame,并实现DataFrame的转置
-
ubuntu环境下利用Wand将pdf转jpg, python代码
-
三行代码使用Python将视频转Gif的方法示例
-
Python调用time模块设置当前时间-指定时间
-
十几行代码带你用Python批量实现txt转xls,方便快捷
-
python3 简明教程 --模块
-
Python中io模块下的StringIO和BytesIO
-
Python3.5 Pandas模块缺失值处理和层次索引实例详解
-
学习python的第十八天(模块导入及使用,关键字,模块搜索路径,python文件的两种用途)