Skip to content

PostgreSQL

PostgresHandler inserts log entries into a PostgreSQL table using psycopg2. The table is created automatically if it does not exist.

Installation

This integration requires the psycopg2-binary package.

bash
uv add logly[postgresql]
bash
pip install "logly[postgresql]"
bash
uv add psycopg2-binary
bash
pip install psycopg2-binary

Missing Dependency

If psycopg2 is not installed, you'll see:

ModuleNotFoundError: No module named 'psycopg2'

Usage

python
from logly import logger
from logly.integrations.postgresql import PostgresHandler

handler = PostgresHandler(
    "postgresql://user:pass@localhost:5432/logs",
    table="app_logs",
)
logger.add(handler, level="WARNING")

Constructor Args

ArgumentTypeDefaultDescription
dsnstrpostgresql://localhost:5432/loglyPostgreSQL connection string
tablestrlogly_logsTable name for log storage
create_tableboolTrueAutomatically create table if it does not exist

Table Schema

The auto-created table has the following schema:

sql
CREATE TABLE IF NOT EXISTS <table> (
    id SERIAL PRIMARY KEY,
    message TEXT NOT NULL,
    timestamp DOUBLE PRECISION NOT NULL,
    created_at TIMESTAMP DEFAULT NOW()
)

Tips

  • Set create_table=False if you manage the schema yourself or want to add custom columns.
  • Use connection pooling in production to avoid one connection per log message.

Full Example

python
from logly import logger
from logly.integrations.postgresql import PostgresHandler

handler = PostgresHandler(
    dsn="postgresql://dbuser:dbpass@db-host:5432/myapp",
    table="app_logs",
    create_table=True,
)
logger.add(handler, level="INFO")

logger.info("Order created", order_id="ord-789")
logger.error("Inventory sync failed")

Released under the MIT License.