如何使用Psycopg2的LoggingConnection? [英] How do I use Psycopg2's LoggingConnection?

查看:116
本文介绍了如何使用Psycopg2的LoggingConnection?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想记录psycopg2进行的查询,但 psycopg2文档并未真正指定应如何使用LoggingConnection。

I'd like to log the queries that psycopg2 is making, but the psycopg2 documentation doesn't really specify how LoggingConnection should be used.

import logging
from psycopg2.extras import LoggingConnection

db_settings = {
    "user": "abcd",
    "password": "efgh",
    "host": "postgres.db",
    "database": "dev",
}

conn = LoggingConnection(**db_settings)

给出错误


LoggingConnection(** db_settings)
TypeError:函数最多接受2个参数(给定5个)

LoggingConnection(**db_settings) TypeError: function takes at most 2 arguments (5 given)


推荐答案

似乎像设置 connection_factory = LoggingConnection 一样

import logging
import psycopg2
from psycopg2.extras import LoggingConnection

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

db_settings = {
    "user": "abcd",
    "password": "efgh",
    "host": "postgres.db",
    "database": "dev",
}

conn = psycopg2.connect(connection_factory=LoggingConnection, **db_settings)
conn.initialize(logger)

cur = conn.cursor()
cur.execute("SELECT * FROM table LIMIT 5")

这篇关于如何使用Psycopg2的LoggingConnection?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆