跳转至

直接数据库连接

Logfire平台允许您使用PostgreSQL语法对数据进行连接和运行SQL查询。

通过执行此操作,您可以将现有工具(例如 Grafana、Metabase、Superset 或其他任何支持查询 PostgreSQL 源的工具)连接起来。

生成凭据

要进行连接,您首先需要从项目页面生成数据库凭据,网址为 https://logfire.pydantic.dev/<organization>/<project>/settings/database-credentials

Creating database credentials

生成的凭据是一个 PostgreSQL URI,可用作兼容工具的连接字符串。这些只会由 Logfire 平台显示一次,因此请将它们保存到安全位置以备将来使用!

连接到数据库

如前所述,您可以使用生成的凭据通过任何支持 PostgreSQL 连接的工具连接到数据库。

使用 pgcli

pgcli 是一个用于访问 PostgreSQL 数据库的命令行工具。

使用上一步中生成的凭据作为 pgcli 的参数,您可以直接连接到 Logfire

$ pgcli postgresql://<user>:<password>@db.logfire.dev:5432/proj_david-test  # REDACTED
Version: 4.0.1
Home: http://pgcli.com
proj_david-test> select start_timestamp, message from records limit 10;
+-------------------------------+----------------------------------------+
| start_timestamp               | message                                |
|-------------------------------+----------------------------------------|
| 2024-04-28 10:50:41.681886+00 | action=view-faq size=549 i=0           |
| 2024-04-28 10:50:41.711747+00 | GET /contact/ http send response.body  |
| 2024-04-28 10:50:41.665576+00 | GET /contact/                          |
| 2024-04-28 10:50:41.711119+00 | GET /contact/ http send response.start |
| 2024-04-28 10:50:41.709458+00 | response 500                           |
| 2024-04-28 10:50:38.505343+00 | action=view-cart size=517 i=0          |
| 2024-04-28 10:50:39.446668+00 | action=view-faq size=637 i=2           |
| 2024-04-28 10:50:38.681198+00 | action=view-terms size=216 i=3         |
| 2024-04-28 10:50:39.416706+00 | action=view-product size=380 i=0       |
| 2024-04-28 10:50:38.394237+00 | sub-sub-sub-action=logout              |
+-------------------------------+----------------------------------------+
SELECT 10
Time: 0.218s

使用 psycopg

psycopg 是一个 Python 库,允许您连接到 PostgreSQL 数据库。

您可以使用上一步生成的凭证连接到Logfire

main.py
import os

import psycopg

POSTGRES_URI = os.getenv('POSTGRES_URI')

with psycopg.connect(POSTGRES_URI) as conn:
    cursor = conn.cursor()
    cursor.execute('SELECT start_timestamp, message FROM records LIMIT 10')
    for start_timestamp, message in cursor.fetchall():
        print(f'{start_timestamp}: {message}')

export POSTGRES_URI=... 环境变量设置为上一步生成的 URI,并使用 python main.py 运行脚本:

2024-04-28 10:50:41.681886+00: action=view-faq size=549 i=0
2024-04-28 10:50:41.711747+00: GET /contact/ http send response.body
2024-04-28 10:50:41.665576+00: GET /contact/
2024-04-28 10:50:41.711119+00: GET /contact/ http send response.start
2024-04-28 10:50:41.709458+00: response 500
2024-04-28 10:50:38.505343+00: action=view-cart size=517 i=0
2024-04-28 10:50:39.446668+00: action=view-faq size=637 i=2
2024-04-28 10:50:38.681198+00: action=view-terms size=216 i=3
2024-04-28 10:50:39.416706+00: action=view-product size=380 i=0
2024-04-28 10:50:38.394237+00: sub-sub-sub-action=logout

凭借您可以灵活访问PostgreSQL的功能,我们迫不及待地想听听您如何使用Logfire!:火灾:


本文总阅读量