日志处理是项目的必备功能,配置合理的日志,可以帮助我们了解系统的运行状况、定位位置,辅助数据分析技术,还可以挖掘出一些额外的系统信息。
本文介绍Python内置的日志处理模块logging的常见用法。
1,日志等级
日志是分等级的,这点不难理解,任何信息都有轻重缓急之分,通过分级,我们可以方便的对日志进行刷选过滤,提高分析效率。
简单说,日志有以下等级:
DEBUG,INFO,WARNING,ERROR,CRITICAL
其重要性依次增强。一般的,这五个等级就足够我们日常使用了。
2,日志格式
日志本质上记录某一事件的发生,那么它应当包括但不限于以下信息:
事件等级,发生时间,地点(代码位置),错误信息
3,logging模块的四大组件
通过这四大组件,我们便可以自由配置自己的日志格式。
4,案例展示
在实际应用中,一般会按照时间或者预置的大小对日志进行定期备份和分割,我们下面就按照这两点分别进行介绍:
4-1,按照预置的文件大小配置日志,并自动分割备份
代码:
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 import logging 4 import logging.handlers 5 import os 6 7 8 def get_logger(): 9 log_path = "./logs" 10 11 if not os.path.isdir(log_path): 12 os.mkdir(log_path) 13 os.chmod(log_path, 0777) 14 15 all_log = log_path + os.path.sep + "all.log" 16 error_log = log_path + os.path.sep + "error.log" 17 18 if not os.path.isfile(all_log): 19 os.mknod(all_log) 20 os.chmod(all_log, 0777) 21 22 if not os.path.isfile(error_log): 23 os.mknod(error_log) 24 os.chmod(error_log, 0777) 25 26 log_format = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") 27 28 # get logger object 29 my_logger = logging.getLogger("my_logger") 30 my_logger.setLevel(logging.DEBUG) 31 32 # auto split log file by interval specified(every minute), record debug message and above. 33 rf_handler = logging.handlers.TimedRotatingFileHandler(all_log, when='M', interval=1, backupCount=3) 34 rf_handler.setLevel(logging.DEBUG) 35 rf_handler.setFormatter(log_format) 36 37 # don't split log file, only record error message and above. 38 f_handler = logging.FileHandler(error_log) 39 f_handler.setLevel(logging.ERROR) 40 f_handler.setFormatter(log_format) 41 42 my_logger.addHandler(rf_handler) 43 my_logger.addHandler(f_handler) 44 45 return my_logger 46 47 48 def test(): 49 msg = {"debug": "This is a debug log", 50 "info": "This is a info log", 51 "warning": "This is a warning log", 52 "error": "This is a error log", 53 "critical": "This is a critical log"} 54 55 for k, v in msg.items(): 56 if k == "debug": 57 logger.debug(v) 58 elif k == "info": 59 logger.info(v) 60 elif k == "warning": 61 logger.warning(v) 62 elif k == "error": 63 logger.error(v) 64 elif k == "critical": 65 logger.critical(v) 66 67 68 if __name__ == '__main__': 69 index = 1 70 logger = get_logger() 71 72 while True: 73 test() 74 print(index) 75 index = index + 1
实际效果:
all.log保存最新的日志,历史副本按照时间后缀进行保存,最多留存三个。
4-2,按照预置的文件大小配置日志,并自动分割备份
代码:
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 import logging 5 from logging.handlers import RotatingFileHandler 6 7 import os 8 9 10 def test(): 11 msg = {"debug": "This is a debug log", 12 "info": "This is a info log", 13 "warning": "This is a warning log", 14 "error": "This is a error log", 15 "critical": "This is a critical log"} 16 17 for k, v in msg.items(): 18 if k == "debug": 19 logger.debug(v) 20 elif k == "info": 21 logger.info(v) 22 elif k == "warning": 23 logger.warning(v) 24 elif k == "error": 25 logger.error(v) 26 elif k == "critical": 27 logger.critical(v) 28 29 30 def get_logger(): 31 dir_path = "./logs" 32 file_name = "rotating_log" 33 if not os.path.isdir(dir_path): 34 os.mkdir(dir_path) 35 os.chmod(dir_path, 0777) 36 37 file_path = dir_path + "/" + file_name 38 if not os.path.isfile(file_path): 39 os.mknod(file_path) 40 os.chmod(file_path, 0777) 41 42 my_logger = logging.getLogger("rotating_log") 43 my_logger.setLevel(level=logging.INFO) 44 45 # auto split log file at max size of 4MB 46 r_handler = RotatingFileHandler(file_path, maxBytes=4*1024*1024, backupCount=3) 47 r_handler.setLevel(logging.INFO) 48 49 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 50 r_handler.setFormatter(formatter) 51 52 my_logger.addHandler(r_handler) 53 54 return my_logger 55 56 57 if __name__ == '__main__': 58 logger = get_logger() 59 index = 1 60 while True: 61 test() 62 print(index) 63 index = index + 1
最终效果: