I'm writting small app in go. And now I need to log postgres "raise notice" message in app console.
I was not found where postgresql raised messages stored in *sql.Conn (I'm use go/sql with lib/pq driver)
example,
create function show_mes() returns int as $$
begin
raise notice 'test message from pg';
return 1;
end
$$ language plpgsql;
from go app I call this function and can get the result.
But how can i access to that messages "test message from pg" from go app?
In current version written in Node we log messages in console for debbugging:
thank you!
If you're using lib/pq
you can use its LISTEN/NOTIFY
support to achieve what you want.
On the Go side you can use something like this:
package main
import (
"log"
"time"
"github.com/lib/pq"
)
func main() {
dburl := "postgres:///?sslmode=disable"
li := pq.NewListener(dburl, 10*time.Second, time.Minute, func(event pq.ListenerEventType, err error) {
if err != nil {
log.Fatal(err)
}
})
if err := li.Listen("raise_notice"); err != nil {
panic(err)
}
for {
select {
case n := <-li.Notify:
// n.Extra contains the payload from the notification
log.Println("notification:", n.Extra)
case <-time.After(5 * time.Minute):
if err := li.Ping(); err != nil {
panic(err)
}
}
}
}
Then your postgres function would look like this:
CREATE FUNCTION show_mes() RETURNS int AS $$
BEGIN
PERFORM pg_notify('raise_notice', 'test message from pg');
RETURN 1;
END
$$ LANGUAGE plpgsql;