psql:将sql错误消息重定向到logfile

问题描述 投票:0回答:1

我需要在块中执行多个psql语句,如下所示。这里我使用“\ o”将查询输出重定向到“logfile”。

但“\ o”仅重定向查询输出,如果发生任何错误,则不包括ERROR消息。

例如:如果我给出了错误的db_name,那么它会在屏幕上显示错误“ERROR:'db_name'不存在”。但是此错误未存储在给定的日志文件中。

有没有办法在同一日志文件中保存错误,其中保存其他输出。

psql -p 5432 -U postgres -h ${db_host} << eof1
\set ON_ERROR_STOP TRUE
\o | cat >> ${logfile}
\l+ db_name;
select pg_database_size('db_name');
\o
eof1
postgresql psql
1个回答
0
投票

将STDERR重定向到文件:

$ psql 2> errors.txt
Expanded display is used automatically.
Null display is "¤".
psql (10.5)
Type "help" for help.

db=# select 1;
 ?column?
----------
        1
(1 row)

db=# select 1 + 'foo';
db=# \q

$ cat errors.txt
ERROR:  invalid input syntax for integer: "foo"
LINE 1: select 1 + 'foo';
                   ^

您还可以在调用psql时指定输出文件,而不是使用\o

$ psql -o out.txt 2> errors.txt
Expanded display is used automatically.
Null display is "¤".
psql (10.5)
Type "help" for help.

db=# select 1;
db=# select 1 + 'foo';
db=# \q

$ cat out.txt
 ?column?
----------
        1
(1 row)

$ cat errors.txt
ERROR:  invalid input syntax for integer: "foo"
LINE 1: select 1 + 'foo';
                   ^
© www.soinside.com 2019 - 2024. All rights reserved.