Skip to content

Instantly share code, notes, and snippets.

@Hanaasagi
Created March 8, 2017 12:49
Show Gist options
  • Save Hanaasagi/ea57a667249fbe8880ed19477fc364a6 to your computer and use it in GitHub Desktop.
Save Hanaasagi/ea57a667249fbe8880ed19477fc364a6 to your computer and use it in GitHub Desktop.
记录慢查询
#!/usr/bin/env python
# encoding: utf-8
import logging
from logging.handlers import RotatingFileHandler
from flask_sqlalchemy import get_debug_queries
# ...
app.config['DATABASE_QUERY_TIMEOUT'] = 0.001
app.config['SQLALCHEMY_RECORD_QUERIES'] = True
formatter = logging.Formatter(
"[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s")
handler = RotatingFileHandler('slow_query.log', maxBytes=10000, backupCount=10)
handler.setlevel(logging.WARN)
handler.setFormatter(formatter)
app.logger.addHandler(handler)
@app.after_request
def after_request(response):
for query in get_debug_queries():
if query.duration >= app.config['DATABASE_QUERY_TIMEOUT']:
app.logger.warn(
('Context:{}\n'
'SLOW QUERY: {}\n'
'Parameters: {}\n'
'Duration: {}\n').format(query.context, query.statement,
query.parameters, query.duration))
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment