|
flask中app.logger是标准logging Logger。
实例:
app.logger.info('!!!!!!!!!!!!!!!!!!!!!!!!')
app.logger.debug('@@@@@@@@@@@@@@')
app.logger.warning('############ (%d apples)', 42)
app.logger.error('$$$$$$$$$$')
控制台输出:
[2018-08-06 06:20:23,231] INFO in logging_test: !!!!!!!!!!!!!!!!!!!!!!!!
[2018-08-06 06:20:23,232] DEBUG in logging_test: @@@@@@@@@@@@@@
[2018-08-06 06:20:23,232] WARNING in logging_test: ############ (42 apples)
[2018-08-06 06:20:23,233] ERROR in logging_test: $$$$$$$$$$
一、日志输出级别
ERROR:非常严重,必须马上处理。
WARN:处理可以继续,但必须要给予额外的关注。
INFO:了解应用正在做什么。
DEBUG和TRACE:开发过程中调试。
二、日志的内容
要求:可读、干净、详细和自描述,注意不能透露一些保密内容。
反模式例子:魔法日志,内容只有开发人员自己能看懂。
三、打印日志
1、app.logger.info('this is a string')
2、message_info = 'the message is %s' % info
app.logger.info(message_info)
3、app.logger.info('the message if %s', info)
四、记录异常信息
使用exception方法,输出内容包括堆栈信息。日志级别为ERROR。
a = [1, 2, 3]
try:
print a[3]
except Exception, e:
logging.exception(e)
输出:
Traceback (most recent call last):
File "/open_falcon/logging_test/logging_test.py", line 46, in login
print a[3]
IndexError: list index out of range
若使用exception又不希望是ERROR级别,可以使用app.logger.info('message info is %s', message, exc_info=1)
五、自定义对异常的处理
@app.errorhandler(500)
def internal_server_error(e):
app.logger.exception('error 500: %s', e)
response = json_error('internal server error')
response.status_code = 500
return response
六、自定义异常
自定义啦 |