Skip to content

Instantly share code, notes, and snippets.

@tristan2077
Created October 16, 2018 03:00
Show Gist options
  • Save tristan2077/d9e8c0563f000af98e36920ffc83fb43 to your computer and use it in GitHub Desktop.
Save tristan2077/d9e8c0563f000af98e36920ffc83fb43 to your computer and use it in GitHub Desktop.
sqlalchemy添加sql执行的语句和时间
from sqlalchemy.engine import Engine
from sqlalchemy import event
import time
import logging
logging.basicConfig()
logger = logging.getLogger("myapp.sqltime")
logger.setLevel(logging.DEBUG)
@event.listens_for(Engine, "before_cursor_execute")
def before_cursor_execute(conn, cursor, statement,
parameters, context, executemany):
context._query_start_time = time.time()
# logger.debug("Start Query:\n%s" % statement)
# Modification for StackOverflow answer:
# Show parameters, which might be too verbose, depending on usage..
# logger.debug("Parameters:\n%r" % (parameters,))
@event.listens_for(Engine, "after_cursor_execute")
def after_cursor_execute(conn, cursor, statement,
parameters, context, executemany):
total = time.time() - context._query_start_time
if total > 1:
logger.debug("SQL:%s" % statement)
# Modification for StackOverflow: times in milliseconds
logger.debug("Total Time: %.02fs" % total)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment