How to get notices to the output stream?
I'm afraid that you won't like this answer, but currently it seems impossible. From the psql documentation:
Saves future query results to the file filename or pipes future results into a separate Unix shell to execute command. If no arguments are specified, the query output will be reset to the standard output.
"Query results" includes all tables, command responses, and notices obtained from the database server, as well as output of various backslash commands that query the database (such as \d), but not error messages.
And as you noticed, there is no way redirecting error messages when using psql
interactively.
(I've been playing around with all kinds of redirection from \o to no avail. It looks like that the query output channel is different from the one getting error messages - and even errors from the server and raised in your procedures go different ways.
test=# SHOW client_min_messages;
client_min_messages
---------------------
notice
-- added the above to show it's not a config problem
CREATE FUNCTION raise_test() RETURNS integer AS
$body$
BEGIN
RAISE NOTICE 'notice';
RETURN 1;
END;
$body$
LANGUAGE plpgsql;
test=# \o | cat > out.sql
test=# SELECT raise_test(); -- you could put this in a file and call \i your_file, it's just the same
NOTICE: notice
test=# \o | cat > out.sql 2>&1
test=# SELECT raise_test();
NOTICE: notice
out.sql contains
raise_test
------------
1
(1 row)
in both cases. This is why I am clueless about what channel/file descriptor is used for outputting the messages raised from a procedure.) )
(There is a thread on PostgreSQL-hackers that may shed some light on this issue: http://postgresql.1045698.n5.nabble.com/psql-output-locations-td5068313.html )
What one could possibly do is starting psql
like
psql test >/tmp/psql.out 2>&1
and this will redirect all output to the specified file. The only problem with this that you don't even have a prompt, and lose the commandline editing capabilities.
We can execute shell command directly from psql using \!
meta command.
localhost:5432 user@db=# \! psql -U user -h localhost your_database -e 'select your_function_name()' > debug.txt 2 >&1
open debug.txt
with \e
.
localhost:5432 user@db=# \e debug.txt
raise message will shown in your default editor. a bit tricky, still quite handy for commandLine lover.