Flask 日志记录
最近项目需要用到flask日志模块来记录日志,这里做下记录:
- 示例代码一
from flask import Flask
import logging
app = Flask(__name__)
handler = logging.FileHandler('app.log' , encoding='UTF-8' )
logging_format = logging.Formatter(
'%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s' )
handler.setFormatter(logging_format)
app.logger.addHandler(handler)
@app.route('/')
def index () :
try :
no_thing = []
i = no_thing[0 ]
return 'Hello!'
except Exception as e:
app.logger.exception('%s' , e)
if __name__ == '__main__' :
app.run(debug=True )
- 示例代码二
如果我们希望打印堆栈信息就可以像下面这样写:
a = [1 , 2 , 3 ]
try :
print a[3 ]
except Exception , e:
logging.exception (e)
message = 'the message is %s' % info
app.logger.info('message info is %s' , message, exc_info=1 )。