如何使用Python在 PostgreSQL 中记录查询?
Python有各种用于 PostgreSQL 的数据库驱动程序。当前最常用的版本是 psycopg2。它完全实现了Python DB-API 2.0 规范。 psycopg2 提供了许多有用的功能,例如客户端和服务器端游标、异步通知和通信、COPY 命令支持等。
安装
安装 psycopg2 模块:
pip install psycopg2
为了记录有关命令的信息,我们需要安装 logtopg:
pip install logtopg
应用
- 信息收集
- 故障排除
- 生成统计信息
- 审计
- 剖析
日志级别及其目的
Level | Purpose |
---|---|
DEBUG | Detailed information, typically of interest only when diagnosing problems. |
INFO | Confirmation that things are working as expected. |
WARNING | An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected. |
ERROR | Due to a more serious problem, the software has not been able to perform some function. |
CRITICAL | A serious error, indicating that the program itself may be unable to continue running. |
所有记录器都是根记录器的后代。根记录器始终具有明确的级别集,默认情况下为 WARNING。根记录器可用于轻松打开和关闭所有库中的所有记录器。
记录器信息显示
Level | Display |
---|---|
debug | Should only appear in the file |
info | Should appear in file |
warning | Should appear in file and stdout |
error | Should appear in file and stdout |
critical | Should appear in file and stdout |
为了更好地理解日志,这里有一个简单的代码,没有连接到 PostgreSQL,它只在控制台中显示消息。
例子:
Python3
import logging
# This will be printed only in file
logging.debug('This is a debug message')
# This will be printed only in file
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')
Python3
import logging
# The getLogger() returns a logger with the specified name.
# If name is None, it returns the root logger.
logger = logging.getLogger('dev')
# Level is set
logger.setLevel(logging.DEBUG)
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message via setLevel')
logger.error('This is an error message via setLevel')
logger.critical('This is a critical message via setLevel')
Python3
#Let this program name be mylib.py
import logging
def from_mylib():
logging.info('I am from mylib')
Python3
#logging module is required to log information
import logging
# User created python code and should be in same directory
import mylib
def main():
# As we have specified myapp.log, all log information will be there
# logging.INFO is the level, it will get printed
logging.basicConfig(filename='myapp.log', level=logging.INFO)
logging.info('Started to print logger info')
# calling mylib method here as have imported. It should be
# in same directory
mylib.from_mylib()
logging.info('Finished logging the information!!!')
# Main code
if __name__ == '__main__':
main()
Python3
import logging
import psycopg2
from psycopg2.extras import LoggingConnection
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("loggerinformation")
# We need to specify the necessary parameters in the below list
# As connecting with postgres/password as username/password and with testdb as parameters
db_settings = {
"user": "postgres",
"password": "password",
"host": "127.0.0.1",
"database": "testdb",
}
# connect to the PostgreSQL server
conn = psycopg2.connect(connection_factory=LoggingConnection, **db_settings)
conn.initialize(logger)
cur = conn.cursor()
cur.execute("SELECT * FROM employee")
Python3
import logging
import psycopg2
from psycopg2.extras import LoggingConnection
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("loggerinformation")
db_settings = {
"user": "postgres",
"password": "password",
"host": "127.0.0.1",
"database": "testdb",
}
conn = psycopg2.connect(connection_factory=LoggingConnection, **db_settings)
conn.initialize(logger)
cur = conn.cursor()
cur.execute("SELECT * FROM employee")
# insert records in employee table
cur.execute(
"INSERT INTO employee (first_name,last_name,age,gender,income) VALUES ('123','456',20,'m',20000)")
输出:
使用了根记录器,只写入了三条消息。这是因为默认情况下,只写入级别警告和级别更高的消息。
下面给出了另一个理解日志级别的例子。日志级别由 setLevel() 设置。
示例 1:
蟒蛇3
import logging
# The getLogger() returns a logger with the specified name.
# If name is None, it returns the root logger.
logger = logging.getLogger('dev')
# Level is set
logger.setLevel(logging.DEBUG)
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message via setLevel')
logger.error('This is an error message via setLevel')
logger.critical('This is a critical message via setLevel')
输出 :
示例 2:
“mylib.py”应该在“sample.py”所在的同一目录中,并且创建的文件“myapp.log”将出现在mylib.py和sample.py所在的同一目录中
mylib.py
蟒蛇3
#Let this program name be mylib.py
import logging
def from_mylib():
logging.info('I am from mylib')
让我们在另一个代码中使用 mylib.py
样本.py
蟒蛇3
#logging module is required to log information
import logging
# User created python code and should be in same directory
import mylib
def main():
# As we have specified myapp.log, all log information will be there
# logging.INFO is the level, it will get printed
logging.basicConfig(filename='myapp.log', level=logging.INFO)
logging.info('Started to print logger info')
# calling mylib method here as have imported. It should be
# in same directory
mylib.from_mylib()
logging.info('Finished logging the information!!!')
# Main code
if __name__ == '__main__':
main()
myapp.log 的输出(在 mylib.py 和 sample.py 所在的同一目录中创建)存在
示例 3:
此示例讨论与 PostgreSQL 与数据库的交互。 pgAdmin 或 psql 是可用于登录 PostgreSQL 数据库服务器的客户端工具。
数据库名称:testdb
表名:员工
蟒蛇3
import logging
import psycopg2
from psycopg2.extras import LoggingConnection
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("loggerinformation")
# We need to specify the necessary parameters in the below list
# As connecting with postgres/password as username/password and with testdb as parameters
db_settings = {
"user": "postgres",
"password": "password",
"host": "127.0.0.1",
"database": "testdb",
}
# connect to the PostgreSQL server
conn = psycopg2.connect(connection_factory=LoggingConnection, **db_settings)
conn.initialize(logger)
cur = conn.cursor()
cur.execute("SELECT * FROM employee")
输出 :
示例 4:
蟒蛇3
import logging
import psycopg2
from psycopg2.extras import LoggingConnection
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("loggerinformation")
db_settings = {
"user": "postgres",
"password": "password",
"host": "127.0.0.1",
"database": "testdb",
}
conn = psycopg2.connect(connection_factory=LoggingConnection, **db_settings)
conn.initialize(logger)
cur = conn.cursor()
cur.execute("SELECT * FROM employee")
# insert records in employee table
cur.execute(
"INSERT INTO employee (first_name,last_name,age,gender,income) VALUES ('123','456',20,'m',20000)")
输出: