python-写日志nnlog模块&异常处理
1.写日志
import nnlog
import traceback
# backCount:保留多久时间的日志,5表示保留最近5天的日志
# when:按什么产生日志文件,D表示按天产生日志文件;S按秒,M按分钟
# level:日志级别;
# log.debug()
# log.info()
# log.error()
# log.warning()
log = nnlog.Logger('python.log',level='debug',backCount=5,when='D')
log.warning("写日志注意了!!")
log.info("第一条info信息")
log.error("出错啦!!")
log.debug("非常详细的日志")
# log.surprise()
def test():
try:
1/0
except Exception:
print('error')
log.error(traceback.format_exc())
return
finally:
print('abc')
test()
2.异常处理
l = [1,2,3]
d = {}
try:
print(l[2])
# print(d['name'])
except Exception as e:
print("出异常了",e)
else:
print("不出异常的时候走到这里")
finally:
print("都会走")
3.练习
import pymysql
import nnlog
mysql_info = {
'host':'xxx',
'port':3306,
'db':'jxz',
'password':'xxx',
'charset':'utf8',
'autocommit':True,
'user':'jxz'
}
log = nnlog.Logger('python.log',level='debug',backCount=5,when='D')
def op_db(sql,one_tag=True):
try:
log.info("开始连接数据库,数据库连接信息是%s"%mysql_info)
connect = pymysql.connect(**mysql_info)
except Exception as e:
log.error("数据库连接失败")
return "001"
else:
log.debug("开始建立游标")
cur = connect.cursor(pymysql.cursors.DictCursor)
try:
log.info("开始执行sql")
log.info("sql语句是%s" %sql)
cur.execute(sql)
except Exception as e:
log.error("sql出错")
return "002"
else:
if one_tag:
result = cur.fetchone()
else:
result = cur.fetchall()
finally:
cur.close()
connect.close()
return result