logger
- 大多数情况下,正常地返回 400 Bad Request 就可以了,但是有时候不能这么做,并且要让代码继续运行。
- 调用日志记录的例子 :
app.logger.debug('A value for debugging')
app.logger.warning('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')
修改默认的logger的名字
python的logging模块
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
handler = logging.FileHandler("log1.txt", mode='w')
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.debug('this is a logger debug message')
logger.info('this is a logger info message')
logger.warning('this is a logger warning message')
logger.error('this is a logger error message')
logger.critical('this is a logger critical message')
logging.basicConfig(filename="login.txt", filemode='a', level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
logger和flask结合使用
import logging
from flask import Flask, request, render_template, flash
app = Flask(__name__)
app.config['SECRET_KEY'] = 'asdfghj'
logging.basicConfig(filename="login.txt", filemode='a', level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger("app")
@app.route('/index')
def index():
app.logger.warning("首页警告")
return render_template('index.html')
- 如果想让app.logger.warning写到文件. logging.getLogger() 必须起名为app