From ef3a120e0ccf74c402f5bacec1c324b12d50356c Mon Sep 17 00:00:00 2001
From: Vignesh C <vignesh21@gmail.com>
Date: Wed, 16 Jul 2025 15:32:41 +0530
Subject: [PATCH v3 3/3] Add custom PQsetNoticeProcessor handlers for fdw
 connection

This patch introduces a custom notice processor for libpq-based
connections in fdw connection. The notice processor captures
messages and routes them through ereport(), making them visible
in local logs with a prefix making it easy for diagnosis.
---
 contrib/postgres_fdw/connection.c | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)

diff --git a/contrib/postgres_fdw/connection.c b/contrib/postgres_fdw/connection.c
index 304f3c20f83..e0f5fb595e3 100644
--- a/contrib/postgres_fdw/connection.c
+++ b/contrib/postgres_fdw/connection.c
@@ -472,6 +472,24 @@ pgfdw_security_check(const char **keywords, const char **values, UserMapping *us
 			 errhint("Target server's authentication method must be changed or password_required=false set in the user mapping attributes.")));
 }
 
+/*
+ * Custom notice processor for libpq connections used by postgres_fdw.
+ */
+static void
+notice_processor(void *arg, const char *message)
+{
+	/* Trim trailing newline for cleaner logs */
+	size_t		len = strlen(message);
+
+	if (len > 0 && message[len - 1] == '\n')
+		ereport(LOG,
+				errmsg("received message from remote server: %.*s",
+					   (int) (len - 1), message));
+	else
+		ereport(LOG,
+				errmsg("received message from remote server: %s", message));
+}
+
 /*
  * Connect to remote server using specified server and user mapping properties.
  */
@@ -625,6 +643,8 @@ connect_pg_server(ForeignServer *server, UserMapping *user)
 							server->servername),
 					 errdetail_internal("%s", pchomp(PQerrorMessage(conn)))));
 
+		PQsetNoticeProcessor(conn, notice_processor, NULL);
+
 		/* Perform post-connection security checks. */
 		pgfdw_security_check(keywords, values, user, conn);
 
-- 
2.43.0

