python学习笔记15:写日志-nnlog模块
一、安装第三方模块nnlog
安装命令为:
pip install nnlog
二、使用实例
1 import nnlog 2 log = nnlog.Logger('python.log') 3 log.warning("xxxx") 4 log.info("xxx") 5 6 # log = nnlog.Logger('python.log',level='warning',backCount=5,when='D') 7 # 默认level日志级别是debug,默认backCount保留日志是5个,默认when时间是按D天产生文件 8 # 日志级别如下: 9 # log.debug() 10 # log.info() 11 # log.warning() #一般是warnig级别 12 # log.error()
三.小练习
1 import pymysql 2 import nnlog 3 import traceback #获取链路模块 4 5 log = nnlog.Logger('python.log',level='debug',backCount=5,when='D') 6 mysql_info = { 7 'host':'118.24.3.40', 8 'user':'jxz', 9 'password':'123456', 10 'db':'jxz', 11 'port':3306, 12 'charset':'utf8', 13 'autocommit':True 14 } 15 16 def op_db(sql,one_tag=True): 17 try: 18 log.debug("开始连接数据库,数据库连接信息是%s"% mysql_info) 19 connect = pymysql.connect(**mysql_info) 20 except Exception as e: 21 log.debug("连接数据失败") 22 log.error("连接数据失败,请检查") 23 log.error(traceback.format_exc()) 24 #traceback.format_exc() #拿到报错的那一段字符串,写到日志里面 25 #traceback.print_exc() #只打印错误信息,不取结果 26 print("数据库连接失败",e) 27 return "001" 28 else: 29 cur = connect.cursor(pymysql.cursors.DictCursor) 30 try: 31 log.debug("开始建立游标") 32 cur.execute(sql) 33 except Exception as e: 34 return "002" 35 else: 36 if one_tag: 37 result = cur.fetchone() 38 else: 39 result = cur.fetchall() 40 41 finally: 42 cur.close() 43 connect.close() 44 return result 45 op_db('sql')