如何使用夜莺监控 PostgreSQL 数据库

秦晓辉@快猫星云 2023年8月21日

其实我个人对 PostgreSQL 不熟,对 PostgreSQL 熟悉的同事都在忙,也不好意思问,我就自己摸索了一下,写了这篇文章,希望对大家有帮助。

配置 Categraf

Categraf 默认带了 PostgreSQL 数据库监控插件,配置文件在:conf/input.postgresql/postgresql.toml。我的简化版本的配置如下:

[[instances]]
address = "host=localhost user=postgres password=1234 sslmode=disable"
outputaddress = "db001"

上面的配置,除了配置数据库连接地址,还额外配置了 outputaddress,相当于给数据库起了一个别名,更容易记忆,你可以按照自己的习惯来命名 outputaddress,一般都是 IP 地址或者业务名。

详细配置参考这里:https://github.com/flashcatcloud/categraf/blob/main/conf/input.postgresql/postgresql.toml

测试 Categraf

通过下面的命令可以测试 postgresql 的插件输出。尤其是 server 那个标签,就是 outputaddress 指定的值,可以按照您的喜好调整,千万不要在这个字段暴露敏感认证信息。

./categraf --test --inputs postgresql

我的输出如下:

...
15:32:14 postgresql_up agent_hostname=ubuntu-linux-22-04-desktop server=db001 1
15:32:14 postgresql_session_time agent_hostname=ubuntu-linux-22-04-desktop db=postgres_global server=db001 0
15:32:14 postgresql_blks_read agent_hostname=ubuntu-linux-22-04-desktop db=postgres_global server=db001 22
15:32:14 postgresql_tup_deleted agent_hostname=ubuntu-linux-22-04-desktop db=postgres_global server=db001 0
15:32:14 postgresql_xact_commit agent_hostname=ubuntu-linux-22-04-desktop db=postgres_global server=db001 0
...

导入大盘

去内置大盘里找到 PostgreSQL 的大盘,克隆自己的业务组就可以使用了:

20230821153507

最终大盘效果:

20230821153616

大家如果觉得大盘有设置不合理的地方,可以自行修改。也欢迎提 PR 给我们。

导入规则

PostgreSQL 也有内置的告警规则:

20230821153725

可以克隆到自己的业务组下调整使用。大家如果觉得这些规则有设置不合理的地方,可以自行调整,也欢迎提 PR 给我们。

自定义采集

仔细查看 conf/input.postgresql/postgresql.toml 配置,可以看到 [[instances.metrics]] 部分,这是自定义 SQL 的地方,如果觉得内置的指标不够用,可以自定义 SQL 语句,采集更多的指标。

各个配置项解释如下:

  • mesurement 指标名。指标名称最终为 postgresql_${mesurement}_${metric_fields}[x] , ${metric_fields}[x]表示metric_fields的元素。
  • request 指定查询监控数据的 sql 语句
  • metrics_fields 返回的列中,指定哪些列作为监控数据的 value 上报
  • label_fields 返回的列中,指定哪些列作为监控数据的 label 上报
  • field_to_append 表示这个列附加到 metric_name 后面,作为 metric_name 的一部分
  • timeout 超时时间

扩展阅读:

开源版
Flashcat
Flashduty