python学习,logging模块封装
1 #!/usr/bin/env python3 2 # -*- coding: utf-8 -*- 3 4 ' Logging module ' 5 '通过封装,每次启动时,log可以根据当前时间新建对应的log文件' 6 7 __author__ = 'qfr' 8 9 import logging # 日志输出 10 from datetime import datetime # 处理日期和时间 11 import os # 调用操作系统提供的接口函数 12 13 def LoggingInit(filePath=os.getcwd(), filename='all.log', level='I'): 14 level_relations = { 15 'D': logging.DEBUG, 16 'I': logging.INFO, 17 'W': logging.WARNING, 18 'E': logging.ERROR, 19 'C': logging.CRITICAL 20 } 21 startTime = datetime.now() 22 filename = startTime.strftime("%Y%m%d_%H%M%S_") + filename 23 filePath = os.path.join(filePath, 'logfiles') # 将所有的log存到一个子文件夹下 24 if not os.path.exists(filePath): # 文件夹不存在,则创建文件夹 25 os.makedirs(filePath) 26 logfilename = os.path.join(filePath, filename) 27 logging.basicConfig( 28 filename=logfilename, 29 level=level_relations[level], 30 format='%(asctime)s [%(levelname)s] : %(message)s --%(filename)s', # 定义输出log的格式 31 filemode='a', # w: 重新写文件; a: 追加在文件后 32 datefmt='%Y-%m-%d %A %H:%M:%S', 33 ) 34 def I(): 35 return logging.info 36 def D(): 37 return logging.debug 38 def E(): 39 return logging.error 40 def W(): 41 return logging.warning 42 43 if __name__=='__main__': 44 LoggingInit() 45 I()('hello !!!') 46 D()('hello !!!') 47 W()('hello !!!') 48 E()('hello !!!')
调用的地方:
1 #!/usr/bin/env python3 2 # -*- coding: utf-8 -*- 3 4 ' GNSS PLL simulation analyze ' 5 'include: 跟踪误差分析和灵敏度分析' 6 '通过设置不同的带宽和积分时间' 7 8 __author__ = 'qfr' 9 10 import sys 11 from datetime import datetime # 处理日期和时间 12 import LoggingQr 13 14 if __name__=='__main__': 15 args = sys.argv 16 LoggingQr.LoggingInit() 17 startTime = datetime.now() 18 LoggingQr.I()('PLL simulation start[%s] !!!', startTime.strftime("%Y-%m-%d %H:%M:%S")) 19 if len(args) == 1: 20 print('Hello, world!') 21 elif len(args) == 2: 22 print('Hello, %s!' % args[1]) 23 else: 24 print('Too many arguments!') 25 endTime = datetime.now() 26 LoggingQr.I()('PLL simulation end[%s] !!!', endTime.strftime("%Y-%m-%d %H:%M:%S")) 27 LoggingQr.I()('run time: %f sec', endTime.timestamp() - startTime.timestamp())
记录每天生活的点点滴滴,呵呵呵呵呵呵

浙公网安备 33010602011771号