参考这篇文章,您应该启用logging_collector
,然后您就可以在log_directory
的log_filename
中看到传入的查询。
为了在docker logs
中启用它,您需要进行一些技巧操作,其中一种解决方案如下:
wrapper.sh:
#!/usr/bin/env bash
mkdir /logs
touch /logs/postgresql.log
chmod -R 777 /logs
tail -f /logs/* &
/docker-entrypoint.sh "$@"
上述代码将使用
tail
监控
/logs/postgresql.log
,这将被
postgresql
的
logging_collector
使用,并在
docker logs
中显示。
Dockerfile:
FROM postgres:11.1-alpine
COPY wrapper.sh /
RUN chmod +x /wrapper.sh
ENTRYPOINT ["/wrapper.sh"]
CMD ["postgres", "-c", "logging_collector=on", "-c", "log_directory=/logs", "-c", "log_filename=postgresql.log", "-c", "log_statement=all"]
上面将使用定制的
wrapper.sh
,它将首先监视 postgre 日志,打印出来,然后继续执行默认的
docker-entrypoint.sh
来启动 postgresql 服务器。
容器启动后,在进入查询之前显示日志:
orange@orange:~/abc$ docker build -t abc:1 .
orange@orange:~/abc$ docker run -idt abc:1
orange@orange:~/abc$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c9112eb785e5 abc:1 "/wrapper.sh postgre…" 2 seconds ago Up 1 second 5432/tcp loving_joliot
orange@orange:~/abc$ docker logs loving_joliot
The files belonging to this database system will be owned by user "postgres".
......
2019-07-13 03:38:14.030 UTC [46] LOG: database system was shut down at 2019-07-13 03:38:13 UTC
2019-07-13 03:38:14.034 UTC [10] LOG: database system is ready to accept connections
模拟一些传入的查询,并再次查看日志:
orange@orange:~/abc$ docker exec -it -u postgres loving_joliot psql -c "SELECT datname FROM pg_database;"
datname
-----------
postgres
template1
template0
(3 rows)
orange@orange:~/abc$ docker logs loving_joliot
The files belonging to this database system will be owned by user "postgres".
......
2019-07-13 03:38:14.030 UTC [46] LOG: database system was shut down at 2019-07-13 03:38:13 UTC
2019-07-13 03:38:14.034 UTC [10] LOG: database system is ready to accept connections
2019-07-13 03:41:22.859 UTC [62] LOG: statement: SELECT datname FROM pg_database;
你可以看到,上面我们模拟了一个 SQL 执行
SELECT datname FROM pg_database;
,在
docker logs
中我们已经可以看到这个 SQL。
postgres:12-alpine
镜像进行测试了?因为我记得在2019年12月这样做并没有起作用... - Florian Fidapostgre:12.3-alpine
。 - Ashishkumar Pandeypostgres:12.3
(PostgreSQL 12.3(Debian 12.3-1.pgdg100+1))的问题。升级到postgres:12.4
解决了我的问题。 - Jonas Knobloch