logging模块
顾名思义,用于程序日志输出,可以设置日志级别、格式、输出方式等,基本使用方法如下:
1、logging.basicConfig方式
简单的配置,只能选择单独输出到屏幕或输出到文件,不能同时输出。例如:
#-*- coding:utf-8 -*- #只能选择输出到屏幕或文件 import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a,%d %b %Y %H:%M:%S', filename='test.log', filemode='a') ''' 参数: level:指定输出的日志级别 format:指定日志格式,包括: asctime:时间 filename:日志归属的文件名称 lineno:日志对应代码在归属文件中的行号 levelname:日至最低级别,不指定默认为warning message:具体的日志内容, datefmt:指定具体的时间格式,如果不指定,asctime将使用默认格式,如:2018-05-05 22:07:30,578 filename:指定日志文件名称,可携带具体路径,不指定该参数时日志输出到屏幕 filemode:指定日志写入模式,默认为'a'表示追加,可以指定为'w'表示覆盖 ''' logging.debug('debug message') logging.info('info message') logging.warning('warning message') logging.error('error message') logging.critical('critical message')
上面例子将日志输出到test.log文件,内容:
Sat,05 May 2018 22:25:14 2.py[line:22] DEBUG debug message Sat,05 May 2018 22:25:14 2.py[line:23] INFO info message Sat,05 May 2018 22:25:14 2.py[line:24] WARNING warning message Sat,05 May 2018 22:25:14 2.py[line:25] ERROR error message Sat,05 May 2018 22:25:14 2.py[line:26] CRITICAL critical message
如果,只需要日志输出到屏幕,只需要将filename='test.log'和filemode='a'两行注释掉即可。
2、logging.getLogger方式
完整配置,即可单独输出到屏幕或文件,也可同时输出。例如:
#-*- coding:utf-8 -*- #日志输出更灵活,可以分别或同时输出到屏幕和文件 import logging #创建一个logger对象 logger=logging.getLogger() #创建一个文件输出流handler,用于写入日志文件 fm=logging.FileHandler('test1.log') #再创建一个标准输出流handler,用于输出到屏幕 pm=logging.StreamHandler() #创建一个日志格式对象 formatter=logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s') #为两个handler添加日志格式 fm.setFormatter(formatter) pm.setFormatter(formatter) #为logger对象添加handler logger.addHandler(fm) logger.addHandler(pm) #设置输出日志级别,默认只输出warning以上 logger.setLevel(logging.DEBUG) logger.debug('debug message') logger.info('info message') logger.warning('warning message') logger.error('error message') logger.critical('critical message')
上面例子,将日志同时输出到屏幕和test1.log文件,内容:
2018-05-05 22:32:52,800 3.py[line:28] DEBUG debug message 2018-05-05 22:32:52,800 3.py[line:29] INFO info message 2018-05-05 22:32:52,800 3.py[line:30] WARNING warning message 2018-05-05 22:32:52,800 3.py[line:31] ERROR error message 2018-05-05 22:32:52,800 3.py[line:32] CRITICAL critical message
logger.addHandler()决定日志输出方向,如果只输出到某一方面,可以将另一行注释掉。
3、具体应用
#!/usr/local/python-3.4/bin/python3.4 #-*- coding:utf-8 -*- import urllib.request import time import logging #这里用于请求某个url,并返回状态码 my_url='http://172.16.1.20:8080/bizmon/BIZServlet?BizCode=DX0001&BatchId=%s' %(int(time.time())) def url_request(): url_response=urllib.request.urlopen(my_url) url_code=url_response.code return url_code #定义自己的日志函数 def get_log(): logger=logging.getLogger() fh=logging.FileHandler('test.log') ph=logging.StreamHandler() formatter=logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s') fh.setFormatter(formatter) logger.addHandler(fh) # logger.addHandler(ph) logger.setLevel(logging.INFO) return logger if __name__ == "__main__": my_log=get_log() try: code=url_request() except Exception: my_log.error("%s request failed!"%(my_url),exc_info=True) #捕获异常,输出到日志中 else: my_log.info("%s request successful! code is %s"%(my_url,code)) #正常日志
日志内容:
2018-05-07 19:41:41,575 16.py[line:28] ERROR http://172.16.1.20:8080/bizmon/BIZServlet?BizCode=DX0001&BatchId=1525693301 request failed! Traceback (most recent call last): File "C:/Users/Administrator/PycharmProjects/first/16.py", line 26, incode=url_request() File "C:/Users/Administrator/PycharmProjects/first/16.py", line 8, in url_request url_response=urllib.request.urlopen(my_url) File "C:\Python3.6\lib\urllib\request.py", line 223, in urlopen return opener.open(url, data, timeout) File "C:\Python3.6\lib\urllib\request.py", line 532, in open response = meth(req, response) File "C:\Python3.6\lib\urllib\request.py", line 642, in http_response 'http', request, response, code, msg, hdrs) File "C:\Python3.6\lib\urllib\request.py", line 570, in error return self._call_chain(*args) File "C:\Python3.6\lib\urllib\request.py", line 504, in _call_chain result = func(*args) File "C:\Python3.6\lib\urllib\request.py", line 650, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 500: Internal Server Error
在捕获异常时,
my_log.error("%s request failed!"%(my_url),exc_info=True)也可写成:my_log.exception("%s request failed!"%(my_url))