Skip to content

Commit c15d62a

Browse files
committed
add documentation section about query logging
1 parent 670d505 commit c15d62a

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

docs/usage.rst

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -409,3 +409,61 @@ Web service that computes the requested power of two.
409409
web.run_app(app)
410410
411411
See :ref:`asyncpg-api-pool` API documentation for more information.
412+
413+
Query logging
414+
=============
415+
416+
Sometimes one may need to see queries being executed.
417+
For example, if they are built dynamically. ``asyncpg`` uses python standard
418+
``logging`` library to emit debug messages of levels ``DEBUG`` and ``TRACE``.
419+
Logging is disabled by default to avoid perfomance affection.
420+
421+
422+
.. note::
423+
``TRACE`` level is custom and not defined inside ``asyncpg``. Define it
424+
yourself if you plan to use it with numeric value ``5``
425+
(using :func:`logging.addLevelName() <python:logging.addLevelName>`) or just
426+
use ``5`` as level value.
427+
428+
429+
.. code-block:: python
430+
431+
import asyncio
432+
import asyncpg
433+
import datetime
434+
import logging
435+
436+
async def main():
437+
# Establish a connection to an existing database named "test"
438+
# as a "postgres" user.
439+
conn = await asyncpg.connect('postgresql://postgres@localhost/test',
440+
query_logging=True)
441+
# Execute a statement to create a new table.
442+
await conn.execute('''
443+
CREATE TABLE users(
444+
id serial PRIMARY KEY,
445+
name text,
446+
dob date
447+
)
448+
''')
449+
450+
# by default root logger level is set to logging.WARNING,
451+
# lets lower it to DEBUG to see the query
452+
logging.getLogger().setLevel(logging.DEBUG)
453+
# Insert a record into the created table.
454+
await conn.execute('''
455+
INSERT INTO users(name, dob) VALUES($1, $2)
456+
''', 'Bob', datetime.date(1984, 3, 1))
457+
458+
# lets lower it to TRACE to see query parameters
459+
logging.getLogger().setLevel(5)
460+
# Select a row from the table.
461+
row = await conn.fetchrow(
462+
'SELECT * FROM users WHERE name = $1', 'Bob')
463+
# *row* now contains
464+
# asyncpg.Record(id=1, name='Bob', dob=datetime.date(1984, 3, 1))
465+
466+
# Close the connection.
467+
await conn.close()
468+
469+
asyncio.get_event_loop().run_until_complete(main())

0 commit comments

Comments
 (0)