Skip to content

asynchronous PG

The logfire.instrument_asyncpg() function can be used to detect asyncpg PostgreSQL drivers usingLogfire.

install

Install logfire using asyncpg extra:

{{ install_logfire(extras=['asyncpg']) }}

usage

Let's set up a PostgreSQL database using Docker and run a Python script that connects to the database using asyncpg to demonstrate how to useLogfirewith asyncpg.

Setting up PostgreSQL databases with Docker

First, we need to initialize a PostgreSQL database. This can be easily done using Docker with the following command:

docker run --name postgres \
    -e POSTGRES_USER=user \
    -e POSTGRES_PASSWORD=secret \
    -e POSTGRES_DB=database \
    -p 5432:5432 -d postgres

This command does the following:

  • --name postgres: Defines the name of the Docker container.

  • -e POSTGRES_USER=user: Set up users for PostgreSQL servers.

  • -e POSTGRES_PASSWORD=secret: Set password for PostgreSQL server.

  • -e POSTGRES_DB=database This creates a new database called database, the same database used in Python scripts.

  • -p 5432:5432 This makes PostgreSQL instances available on the local machine under port 5432.

  • -d postgres: This indicates the Docker image to use, in this case "postgres".

run a Python script

The following Python script connects to a PostgreSQL database and executes some SQL queries:

import asyncio

import asyncpg

import logfire

logfire.configure()
logfire.instrument_asyncpg()


async def main():
    connection: asyncpg.Connection = await asyncpg.connect(
        user='user', password='secret', database='database', host='0.0.0.0', port=5432
    )

    with logfire.span('Create table and insert data'):
        await connection.execute('CREATE TABLE IF NOT EXISTS test (id serial PRIMARY KEY, num integer, data varchar);')

        # Insert some data
        await connection.execute('INSERT INTO test (num, data) VALUES ($1, $2)', 100, 'abc')
        await connection.execute('INSERT INTO test (num, data) VALUES ($1, $2)', 200, 'def')

        # Query the data
        for record in await connection.fetch('SELECT * FROM test'):
            logfire.info('Retrieved {record=}', record=record)


asyncio.run(main())

If you go to the project on the UI, you will see the span created by the script.


本文总阅读量次