python logging怎么记录报错
基本范式是:
try:
do-something-block
except:
logger.exception("Exception Logged")
[python] view plain copy
def setLogger():
# 创建一个logger,可以考虑如何将它封装
logger = logging.getLogger('mylogger')
logger.setLevel(logging.DEBUG)
# 创建一个handler,用于写入日志文件
fh = logging.FileHandler(os.path.join(os.getcwd(), 'log.txt'))
fh.setLevel(logging.DEBUG)
# 再创建一个handler,用于输出到控制台
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# 定义handler的输出格式
formatter = logging.Formatter('%(asctime)s - %(module)s.%(funcName)s.%(lineno)d - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# 给logger添加handler
logger.addHandler(fh)
logger.addHandler(ch)
# 记录一条日志
logger.info('hello world, i\'m log helper in python, may i help you')
return logger
#对单个表插入一个元组,其定义有
def insertOneData(conn,tableName,listColumn,lData):
try:
cursor=conn.cursor()
sql="insert into "+tableName+"("
i=0
length=len(listColumn)
for column in listColumn:
if(i!=(length-1)):
sql=sql+column+","
else:
sql=sql+column+") values("
i=i+1
for i in range(0,length):
if(i!=(length-1)):
sql=sql+"%s,"
else:
sql=sql+"%s);"
logger.info(sql)
logger.info(lData)
cursor.execute(sql,lData);
conn.commit()
except:
logger.exception("Exception Logged")
日志的记录形式如下:
2012-04-30 22:29:39,173 - __init__.copyDataWithReplace.135 - ERROR - Exception Logged
Traceback (most recent call last):
File "C:\Eclipse Java EE workspace\ReadExcel\tw_to_microblog\__init__.py", line 133, in copyDataWithReplace
insertOneData(newConn,newTbl,newColList,lData)
File "C:\Eclipse java EE workspace\ReadExcel\tw_to_microblog\__init__.py", line 156, in insertOneData
cursor.execute(sql,lData);
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
IntegrityError: (1062, "Duplicate entry '95322' for key 'PRIMARY'")