logging模块
如何在python中创建日志系统呢? 很简单.
1. 导入logging模块.
2. 简单配置一下logging
3. 出现异常的时候(except). 向日志里写错误信息.
1 import logging 2 3 logging.basicConfig( 4 filename='app.log', 5 format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', 6 datefmt='%Y-%m-%d %H:%M:%S', 7 level=0 # level 设置级别. 当你的信息的级别>=level的时候才会写入日志文件, 默认30 8 ) 9 10 logging.critical("我是critical") # 50分. 11 logging.error("我是error") # 40分 12 logging.warning("我是警告") # 警告 30 13 logging.info("我是基本信息") # 20 14 logging.debug("我是调试") # 10 15 logging.log(2, "我是自定义") # 自定义.
1 # 测试 2 import traceback 3 import logging 4 5 logging.basicConfig( 6 filename='app.log', 7 format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', 8 datefmt='%Y-%m-%d %H:%M:%S', 9 level=0 # level 设置级别. 当你的信息的级别>=level的时候才会写入日志文件, 默认30 10 ) 11 12 for i in range(10): 13 try: 14 if i % 3 == 0: 15 raise FileNotFoundError 16 elif i % 2 == 0: 17 raise KeyError 18 elif i % 5 == 0: 19 raise ResourceWarning 20 except ResourceWarning as e: 21 val = traceback.format_exc() 22 logging.warning(val) 23 except FileNotFoundError as e: 24 val = traceback.format_exc() 25 logging.error(val) 26 except KeyError as e: 27 val = traceback.format_exc() 28 logging.error(val)
1 # 多文件日志处理 2 import logging 3 4 # 创建⼀个操作日志的对象logger(依赖FileHandler) 5 file_handler = logging.FileHandler('l1.log', 'a', encoding='utf-8') 6 # 设置日志文件内容的格式 7 file_handler.setFormatter(logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s")) 8 logger1 = logging.Logger('A', level=40) 9 logger1.addHandler(file_handler) 10 # 记录日志 11 logger1.error('我是A系统') 12 13 # 再创建⼀个操作⽇志的对象logger(依赖FileHandler) 14 file_handler2 = logging.FileHandler('l2.log', 'a', encoding='utf-8') 15 file_handler2.setFormatter(logging.Formatter(fmt="%(asctime)s - %(name)s -%(levelname)s -%(module)s: %(message)s")) 16 logger2 = logging.Logger('B', level=40) 17 logger2.addHandler(file_handler2) 18 # 记录日志 19 logger2.error('我是B系统')