long2ice / asyncmy

A fast asyncio MySQL/MariaDB driver with replication protocol support
https://github.com/long2ice/asyncmy
Apache License 2.0
230 stars 25 forks source link

echo=True outputs as "info" instead of "debug" and feature request query_callback #81

Open WilliamStam opened 8 months ago

WilliamStam commented 8 months ago

im looking to keep track of all statements executed. right now iecho=True outputs to logging info.

if self._echo:
        logger.info(f"[{round((end - start) * 1000, 2)}ms] {query}")

would it be possible in future to set it to logger.debug instead?

would be very useful if you could pass in a callable for returning the exact statement executed on every statement. which would return a float for time taken and string of statement executed.

this would allow for things like being able to "slow query" log applications n stuff.

# replace echo=True
def query_callback(cursor: Cursor, query:str, timer:float):
    logger.info(f"[{timer}ms] {query}")
cursor.query_callback = query_callback

# ----
# log slow queries
def query_callback(cursor: Cursor, query:str, timer:float):
    if timer > 1000:
        logger.warning(f"[{timer}ms] {query}")
cursor.query_callback = query_callback

then in cursors.pyx

def __init__(self, connection: "Connection", echo: bool = False, query_callback = None):
    self._query_callback = query_callback 
...

if self._echo:
    logger.info(f"[{round((end - start) * 1000, 2)}ms] {query}")

if callable(self._query_callback):
    self._query_callback(self,query,round((end - start) * 1000, 2))

wouldn't break backwards compatibility since echo=True could just be a kickstarter to add a log.info() callable if no callable is supplied


def query_callback(cursor: Cursor, query:str, timer:float):
    logger.info(f"[{timer}ms] {query}")

def __init__(self, connection: "Connection", echo: bool = False, query_callback = None):
    if echo and not callable(query_callback):
        self._query_callback = query_callback 
...