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

This patch introduces a custom notice processor for libpq-based
connections in replication 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.
---
 .../libpqwalreceiver/libpqwalreceiver.c       | 20 +++++++++++++++++++
 1 file changed, 20 insertions(+)

diff --git a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
index f7b5d093681..93b71805df4 100644
--- a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
+++ b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
@@ -127,6 +127,24 @@ _PG_init(void)
 	WalReceiverFunctions = &PQWalReceiverFunctions;
 }
 
+/*
+ * Custom notice processor for libpq connections used by replication.
+ */
+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 via replication: %.*s",
+					   (int) (len - 1), message));
+	else
+		ereport(LOG,
+				errmsg("received message via replication: %s", message));
+}
+
 /*
  * Establish the connection to the primary server.
  *
@@ -232,6 +250,8 @@ libpqrcv_connect(const char *conninfo, bool replication, bool logical,
 				 errhint("Target server's authentication method must be changed, or set password_required=false in the subscription parameters.")));
 	}
 
+	PQsetNoticeProcessor(conn->streamConn, notice_processor, NULL);
+
 	/*
 	 * Set always-secure search path for the cases where the connection is
 	 * used to run SQL queries, so malicious users can't get control.
-- 
2.43.0

