From bb2b399ead730108f16f19d3e9833afef5ba2b38 Mon Sep 17 00:00:00 2001
From: Ilya Staroverov <i.staroverov@ftdata.ru>
Date: Fri, 27 Nov 2026 09:12:02 +0300
Subject: [PATCH v1 2/2] Add an opt-in UTF-8 encoding for server logs

Add log_encoding=off|utf8 for stderr, csvlog, jsonlog and syslog.
Convert before serialization, preserve invalid bytes as escapes, and
use a bounded fallback if the conversion buffer cannot be allocated.

Author: Ilya Staroverov <i.staroverov@ftdata.ru>
Discussion: https://postgr.es/m/20090415135043.C439.52131E4D@oss.ntt.co.jp
Co-authored-by: Itagaki Takahiro <itagaki.takahiro@oss.ntt.co.jp>
---
 doc/src/sgml/config.sgml                      |  34 +++
 src/backend/utils/error/csvlog.c              |  50 +++-
 src/backend/utils/error/elog.c                | 236 +++++++++++++-----
 src/backend/utils/error/jsonlog.c             |  43 +++-
 src/backend/utils/mb/Makefile                 |   1 +
 src/backend/utils/mb/log_encoding.c           | 170 +++++++++++++
 src/backend/utils/mb/mbutils.c                |  33 ++-
 src/backend/utils/mb/meson.build              |   1 +
 src/backend/utils/misc/guc_parameters.dat     |   7 +
 src/backend/utils/misc/guc_tables.c           |   7 +
 src/backend/utils/misc/postgresql.conf.sample |   1 +
 src/include/mb/pg_wchar.h                     |   1 +
 src/include/utils/elog.h                      |  12 +-
 src/test/modules/test_misc/meson.build        |   1 +
 .../modules/test_misc/t/017_log_encoding.pl   | 135 ++++++++++
 src/tools/pgindent/typedefs.list              |   1 +
 16 files changed, 649 insertions(+), 84 deletions(-)
 create mode 100644 src/backend/utils/mb/log_encoding.c
 create mode 100644 src/test/modules/test_misc/t/017_log_encoding.pl

diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index 28440932a7..bd5c5ab936 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -7173,6 +7173,40 @@ local0.*    /var/log/postgresql
       </listitem>
      </varlistentry>
 
+     <varlistentry id="guc-log-encoding" xreflabel="log_encoding">
+      <term><varname>log_encoding</varname> (<type>enum</type>)
+      <indexterm>
+       <primary><varname>log_encoding</varname> configuration parameter</primary>
+      </indexterm>
+      </term>
+      <listitem>
+       <para>
+        When set to <literal>utf8</literal>, the server logging system writes
+        messages to <literal>stderr</literal>, <literal>csvlog</literal>,
+        <literal>jsonlog</literal>, and <literal>syslog</literal> in UTF-8.
+        For input of unknown encoding, including data from
+        <literal>SQL_ASCII</literal> databases, valid UTF-8 sequences are
+        preserved.  Bytes that cannot be converted are written as hexadecimal
+        escapes.  User and database names of unknown encoding in
+        <varname>log_line_prefix</varname> use hexadecimal escapes for all
+        bytes outside printable ASCII.  Literal text in
+        <varname>log_line_prefix</varname> should be configured in UTF-8.
+        If memory for conversion is unavailable, the converted message may
+        be truncated.  The default is <literal>off</literal>, which retains
+        the source encoding of each message.  This parameter can only be set
+        at server start.
+       </para>
+       <para>
+        This setting applies after server configuration has been processed.
+        It does not change client messages or the Windows event log.  Raw
+        output captured by the logging collector, for example from external
+        programs, can still contain bytes in other encodings.  When changing
+        encoding, use a new log file to avoid appending UTF-8 messages to
+        older files containing other encodings.
+       </para>
+      </listitem>
+     </varlistentry>
+
      <varlistentry id="guc-logging-collector" xreflabel="logging_collector">
       <term><varname>logging_collector</varname> (<type>boolean</type>)
       <indexterm>
diff --git a/src/backend/utils/error/csvlog.c b/src/backend/utils/error/csvlog.c
index ee4e2a7104..d78195f6e3 100644
--- a/src/backend/utils/error/csvlog.c
+++ b/src/backend/utils/error/csvlog.c
@@ -18,6 +18,7 @@
 #include "access/xact.h"
 #include "lib/stringinfo.h"
 #include "libpq/libpq-be.h"
+#include "mb/pg_wchar.h"
 #include "miscadmin.h"
 #include "postmaster/syslogger.h"
 #include "storage/lock.h"
@@ -34,15 +35,20 @@
  * If it's NULL, append nothing.
  */
 static inline void
-appendCSVLiteral(StringInfo buf, const char *data)
+appendCSVLiteralEncoding(StringInfo buf, const char *data, int encoding)
 {
-	const char *p = data;
+	LogEncodingBuffer buffer;
+	const char *p;
 	char		c;
 
 	/* avoid confusing an empty string with NULL */
-	if (p == NULL)
+	if (data == NULL)
 		return;
 
+	buffer.allocated = NULL;
+	p = data;
+	if (Log_encoding == PG_UTF8)
+		p = log_convert_text(data, -1, encoding, &buffer);
 	appendStringInfoCharMacro(buf, '"');
 	while ((c = *p++) != '\0')
 	{
@@ -51,6 +57,30 @@ appendCSVLiteral(StringInfo buf, const char *data)
 		appendStringInfoCharMacro(buf, c);
 	}
 	appendStringInfoCharMacro(buf, '"');
+	if (buffer.allocated)
+		pfree(buffer.allocated);
+}
+
+static inline void
+appendCSVLiteral(StringInfo buf, const char *data)
+{
+	appendCSVLiteralEncoding(buf, data, log_source_encoding());
+}
+
+static void
+appendCSVUnquoted(StringInfo buf, const char *data, int encoding)
+{
+	LogEncodingBuffer buffer;
+
+	if (Log_encoding != PG_UTF8)
+	{
+		appendStringInfoString(buf, data);
+		return;
+	}
+
+	appendStringInfoString(buf, log_convert_text(data, -1, encoding, &buffer));
+	if (buffer.allocated)
+		pfree(buffer.allocated);
 }
 
 /*
@@ -87,17 +117,19 @@ write_csvlog(ErrorData *edata)
 	initStringInfo(&buf);
 
 	/* timestamp with milliseconds */
-	appendStringInfoString(&buf, get_formatted_log_time());
+	appendCSVUnquoted(&buf, get_formatted_log_time(), log_source_encoding());
 	appendStringInfoChar(&buf, ',');
 
 	/* username */
 	if (MyProcPort)
-		appendCSVLiteral(&buf, MyProcPort->user_name);
+		appendCSVLiteralEncoding(&buf, MyProcPort->user_name,
+								 GetDatabaseEncoding());
 	appendStringInfoChar(&buf, ',');
 
 	/* database name */
 	if (MyProcPort)
-		appendCSVLiteral(&buf, MyProcPort->database_name);
+		appendCSVLiteralEncoding(&buf, MyProcPort->database_name,
+								 GetDatabaseEncoding());
 	appendStringInfoChar(&buf, ',');
 
 	/* Process id  */
@@ -109,7 +141,7 @@ write_csvlog(ErrorData *edata)
 	if (MyProcPort && MyProcPort->remote_host)
 	{
 		appendStringInfoChar(&buf, '"');
-		appendStringInfoString(&buf, MyProcPort->remote_host);
+		appendCSVUnquoted(&buf, MyProcPort->remote_host, log_source_encoding());
 		if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
 		{
 			appendStringInfoChar(&buf, ':');
@@ -145,7 +177,7 @@ write_csvlog(ErrorData *edata)
 	appendStringInfoChar(&buf, ',');
 
 	/* session start timestamp */
-	appendStringInfoString(&buf, get_formatted_start_time());
+	appendCSVUnquoted(&buf, get_formatted_start_time(), log_source_encoding());
 	appendStringInfoChar(&buf, ',');
 
 	/* Virtual transaction id */
@@ -159,7 +191,7 @@ write_csvlog(ErrorData *edata)
 	appendStringInfoChar(&buf, ',');
 
 	/* Error severity */
-	appendStringInfoString(&buf, _(error_severity(edata->elevel)));
+	appendCSVUnquoted(&buf, _(error_severity(edata->elevel)), GetMessageEncoding());
 	appendStringInfoChar(&buf, ',');
 
 	/* SQL state code */
diff --git a/src/backend/utils/error/elog.c b/src/backend/utils/error/elog.c
index e215ed053f..4e73abb7b1 100644
--- a/src/backend/utils/error/elog.c
+++ b/src/backend/utils/error/elog.c
@@ -72,6 +72,7 @@
 
 #include "access/xact.h"
 #include "common/ip.h"
+#include "common/string.h"
 #include "libpq/libpq.h"
 #include "libpq/pqformat.h"
 #include "mb/pg_wchar.h"
@@ -114,6 +115,7 @@ emit_log_hook_type emit_log_hook = NULL;
 int			Log_error_verbosity = PGERROR_DEFAULT;
 char	   *Log_line_prefix = NULL; /* format for extra log line info */
 int			Log_destination = LOG_DESTINATION_STDERR;
+int			Log_encoding = PG_SQL_ASCII;
 char	   *Log_destination_string = NULL;
 bool		syslog_sequence_numbers = true;
 bool		syslog_split_messages = true;
@@ -197,9 +199,10 @@ static void backtrace_cleanup(int code, Datum arg);
 static void set_errdata_field(MemoryContextData *cxt, char **ptr, const char *str);
 static void FreeErrorDataContents(ErrorData *edata);
 static int	log_min_messages_cmp(const ListCell *a, const ListCell *b);
-static void write_console(const char *line, int len);
+static void write_console(const char *line, int len, int encoding);
 static const char *process_log_prefix_padding(const char *p, int *ppadding);
-static void log_line_prefix(StringInfo buf, ErrorData *edata);
+static void format_log_status(StringInfo buf, const char *format,
+							  ErrorData *edata, StringInfo utf8);
 static void send_message_to_server_log(ErrorData *edata);
 static void send_message_to_frontend(ErrorData *edata);
 static void append_with_tabs(StringInfo buf, const char *str);
@@ -2823,6 +2826,13 @@ assign_syslog_facility(int newval, void *extra)
 
 #ifdef HAVE_SYSLOG
 
+/* In a UTF-8 message a high-bit byte may be part of a character. */
+static inline bool
+is_log_space(unsigned char c)
+{
+	return (Log_encoding != PG_UTF8 || !IS_HIGHBIT_SET(c)) && isspace(c);
+}
+
 /*
  * Write a message line to syslog
  */
@@ -2889,18 +2899,21 @@ write_syslog(int level, const char *line)
 			buf[buflen] = '\0';
 
 			/* trim to multibyte letter boundary */
-			buflen = pg_mbcliplen(buf, buflen, buflen);
+			if (Log_encoding == PG_UTF8)
+				buflen = pg_encoding_mbcliplen(PG_UTF8, buf, buflen, buflen);
+			else
+				buflen = pg_mbcliplen(buf, buflen, buflen);
 			if (buflen <= 0)
 				return;
 			buf[buflen] = '\0';
 
 			/* already word boundary? */
 			if (line[buflen] != '\0' &&
-				!isspace((unsigned char) line[buflen]))
+				!is_log_space(line[buflen]))
 			{
 				/* try to divide at word boundary */
 				i = buflen - 1;
-				while (i > 0 && !isspace((unsigned char) buf[i]))
+				while (i > 0 && !is_log_space(buf[i]))
 					i--;
 
 				if (i > 0)		/* else couldn't divide word boundary */
@@ -3047,11 +3060,12 @@ write_eventlog(int level, const char *line, int len)
 #endif							/* WIN32 */
 
 static void
-write_console(const char *line, int len)
+write_console(const char *line, int len, int encoding)
 {
 	ssize_t		rc;
 
 #ifdef WIN32
+	HANDLE		stdHandle = GetStdHandle(STD_ERROR_HANDLE);
 
 	/*
 	 * Try to convert the message to UTF16 and write it with WriteConsoleW().
@@ -3063,8 +3077,7 @@ write_console(const char *line, int len)
 	 * stderr into binary mode in SubPostmasterMain(), write() skips the
 	 * necessary translation anyway.
 	 *
-	 * WriteConsoleW() will fail if stderr is redirected, so just fall through
-	 * to writing unconverted to the logfile in this case.
+	 * A file or pipe cannot be a console.  Skip conversion in that case.
 	 *
 	 * Since we palloc the structure required for conversion, also fall
 	 * through to writing unconverted if we have not yet set up
@@ -3072,18 +3085,17 @@ write_console(const char *line, int len)
 	 */
 	if (!in_error_recursion_trouble() &&
 		!redirection_done &&
-		CurrentMemoryContext != NULL)
+		CurrentMemoryContext != NULL &&
+		GetFileType(stdHandle) == FILE_TYPE_CHAR)
 	{
 		WCHAR	   *utf16;
 		int			utf16len;
 
-		utf16 = pgwin32_message_to_UTF16(line, len, &utf16len);
+		utf16 = pgwin32_to_UTF16(line, len, &utf16len, encoding);
 		if (utf16 != NULL)
 		{
-			HANDLE		stdHandle;
 			DWORD		written;
 
-			stdHandle = GetStdHandle(STD_ERROR_HANDLE);
 			if (WriteConsoleW(stdHandle, utf16, utf16len, &written, NULL))
 			{
 				pfree(utf16);
@@ -3097,15 +3109,6 @@ write_console(const char *line, int len)
 			pfree(utf16);
 		}
 	}
-#else
-
-	/*
-	 * Conversion on non-win32 platforms is not implemented yet. It requires
-	 * non-throw version of pg_do_encoding_conversion(), that converts
-	 * unconvertible characters to '?' without errors.
-	 *
-	 * XXX: We have a no-throw version now. It doesn't convert to '?' though.
-	 */
 #endif
 
 	/*
@@ -3277,12 +3280,79 @@ process_log_prefix_padding(const char *p, int *ppadding)
 }
 
 /*
- * Format log status information using Log_line_prefix.
+ * Convert a complete segment before adding bytes from another source.  The
+ * two buffers are normally the same.  When also writing to the Windows
+ * event log, retain the original bytes in buf.
+ */
+static void
+convert_log_segment(StringInfo utf8, StringInfo buf, int start, int encoding)
+{
+	LogEncodingBuffer buffer;
+	const char *text = buf->data + start;
+	int			len = buf->len - start;
+	const char *converted = log_convert_text(text, len, encoding, &buffer);
+
+	if (converted != text)
+	{
+		if (utf8 == buf)
+			buf->len = start;
+		appendStringInfoString(utf8, converted);
+	}
+	else if (utf8 != buf)
+		appendBinaryStringInfo(utf8, text, len);
+
+	if (buffer.allocated)
+		pfree(buffer.allocated);
+}
+
+/*
+ * Finish the preceding message text, then format the next line's prefix.
+ * The configuration file and the database can use different encodings.
  */
 static void
-log_line_prefix(StringInfo buf, ErrorData *edata)
+log_line_prefix(StringInfo buf, ErrorData *edata, StringInfo utf8,
+				int *body_start)
 {
-	log_status_format(buf, Log_line_prefix, edata);
+	if (utf8 && buf->len > *body_start)
+		convert_log_segment(utf8, buf, *body_start,
+							log_source_encoding());
+
+	format_log_status(buf, Log_line_prefix, edata, utf8);
+	*body_start = buf->len;
+}
+
+/*
+ * Startup packet names and names in SQL_ASCII databases have no declared
+ * encoding.  Keep their bytes printable in the formatted log prefix.
+ */
+static void
+append_log_name(StringInfo buf, const char *name, int padding)
+{
+	char	   *escaped = NULL;
+
+	if (name == NULL || *name == '\0')
+		name = _("[unknown]");
+	else if (Log_encoding == PG_UTF8 && GetDatabaseEncoding() == PG_SQL_ASCII)
+	{
+		const unsigned char *p = (const unsigned char *) name;
+
+		for (; *p != '\0'; p++)
+		{
+			if (*p < 32 || *p > 126)
+			{
+				escaped = pg_clean_ascii(name, MCXT_ALLOC_NO_OOM);
+				name = escaped ? escaped : "[unknown]";
+				break;
+			}
+		}
+	}
+
+	if (padding != 0)
+		appendStringInfo(buf, "%*s", padding, name);
+	else
+		appendStringInfoString(buf, name);
+	if (escaped)
+		pfree(escaped);
 }
 
 /*
@@ -3290,6 +3360,13 @@ log_line_prefix(StringInfo buf, ErrorData *edata)
  */
 void
 log_status_format(StringInfo buf, const char *format, ErrorData *edata)
+{
+	format_log_status(buf, format, edata, NULL);
+}
+
+static void
+format_log_status(StringInfo buf, const char *format, ErrorData *edata,
+				  StringInfo utf8)
 {
 	/* static counter for line numbers */
 	static long log_line_number = 0;
@@ -3318,10 +3395,18 @@ log_status_format(StringInfo buf, const char *format, ErrorData *edata)
 
 	for (p = format; *p != '\0'; p++)
 	{
+		int			start = buf->len;
+		int			encoding = utf8 ? log_source_encoding() : PG_SQL_ASCII;
+
 		if (*p != '%')
 		{
-			/* literal char, just copy */
-			appendStringInfoChar(buf, *p);
+			int			len = strcspn(p, "%");
+
+			appendBinaryStringInfo(buf, p, len);
+			/* The literal bytes come from configuration, not the database. */
+			if (utf8)
+				convert_log_segment(utf8, buf, start, PG_SQL_ASCII);
+			p += len - 1;
 			continue;
 		}
 
@@ -3333,6 +3418,8 @@ log_status_format(StringInfo buf, const char *format, ErrorData *edata)
 		{
 			/* string contains %% */
 			appendStringInfoChar(buf, '%');
+			if (utf8 && utf8 != buf)
+				appendStringInfoChar(utf8, '%');
 			continue;
 		}
 
@@ -3365,7 +3452,10 @@ log_status_format(StringInfo buf, const char *format, ErrorData *edata)
 					const char *appname = application_name;
 
 					if (appname == NULL || *appname == '\0')
+					{
 						appname = _("[unknown]");
+						encoding = GetMessageEncoding();
+					}
 					if (padding != 0)
 						appendStringInfo(buf, "%*s", padding, appname);
 					else
@@ -3388,32 +3478,14 @@ log_status_format(StringInfo buf, const char *format, ErrorData *edata)
 				}
 			case 'u':
 				if (MyProcPort)
-				{
-					const char *username = MyProcPort->user_name;
-
-					if (username == NULL || *username == '\0')
-						username = _("[unknown]");
-					if (padding != 0)
-						appendStringInfo(buf, "%*s", padding, username);
-					else
-						appendStringInfoString(buf, username);
-				}
+					append_log_name(buf, MyProcPort->user_name, padding);
 				else if (padding != 0)
 					appendStringInfoSpaces(buf,
 										   padding > 0 ? padding : -padding);
 				break;
 			case 'd':
 				if (MyProcPort)
-				{
-					const char *dbname = MyProcPort->database_name;
-
-					if (dbname == NULL || *dbname == '\0')
-						dbname = _("[unknown]");
-					if (padding != 0)
-						appendStringInfo(buf, "%*s", padding, dbname);
-					else
-						appendStringInfoString(buf, dbname);
-				}
+					append_log_name(buf, MyProcPort->database_name, padding);
 				else if (padding != 0)
 					appendStringInfoSpaces(buf,
 										   padding > 0 ? padding : -padding);
@@ -3466,6 +3538,7 @@ log_status_format(StringInfo buf, const char *format, ErrorData *edata)
 					appendStringInfo(buf, "%ld", log_line_number);
 				break;
 			case 'm':
+				encoding = PG_SQL_ASCII;
 				/* force a log timestamp reset */
 				formatted_log_time[0] = '\0';
 				(void) get_formatted_log_time();
@@ -3476,6 +3549,7 @@ log_status_format(StringInfo buf, const char *format, ErrorData *edata)
 					appendStringInfoString(buf, formatted_log_time);
 				break;
 			case 't':
+				encoding = PG_SQL_ASCII;
 				{
 					pg_time_t	stamp_time = (pg_time_t) time(NULL);
 					char		strfbuf[128];
@@ -3510,6 +3584,7 @@ log_status_format(StringInfo buf, const char *format, ErrorData *edata)
 				}
 				break;
 			case 's':
+				encoding = PG_SQL_ASCII;
 				{
 					char	   *start_time = get_formatted_start_time();
 
@@ -3568,6 +3643,7 @@ log_status_format(StringInfo buf, const char *format, ErrorData *edata)
 				}
 				break;
 			case 'r':
+				encoding = PG_SQL_ASCII;
 				if (MyProcPort && MyProcPort->remote_host)
 				{
 					if (padding != 0)
@@ -3606,6 +3682,7 @@ log_status_format(StringInfo buf, const char *format, ErrorData *edata)
 										   padding > 0 ? padding : -padding);
 				break;
 			case 'h':
+				encoding = PG_SQL_ASCII;
 				if (MyProcPort && MyProcPort->remote_host)
 				{
 					if (padding != 0)
@@ -3666,6 +3743,8 @@ log_status_format(StringInfo buf, const char *format, ErrorData *edata)
 				/* format error - ignore it */
 				break;
 		}
+		if (utf8 && buf->len > start)
+			convert_log_segment(utf8, buf, start, encoding);
 	}
 }
 
@@ -3697,11 +3776,34 @@ static void
 send_message_to_server_log(ErrorData *edata)
 {
 	StringInfoData buf;
+#ifdef WIN32
+	StringInfoData utf8;
+#endif
+	StringInfo	converted = NULL;
+	int			body_start = 0;
+	const char *log_text;
+	int			log_len;
 	bool		fallback_to_stderr = false;
 
 	initStringInfo(&buf);
+	if (Log_encoding == PG_UTF8 &&
+		((Log_destination & (LOG_DESTINATION_STDERR | LOG_DESTINATION_SYSLOG)) ||
+		 whereToSendOutput == DestDebug || syslogger_setup_done ||
+		 (!redirection_done &&
+		  (Log_destination & (LOG_DESTINATION_CSVLOG | LOG_DESTINATION_JSONLOG)))))
+	{
+		converted = &buf;
+#ifdef WIN32
+		if ((Log_destination & LOG_DESTINATION_EVENTLOG) ||
+			(!redirection_done && pgwin32_is_service()))
+		{
+			initStringInfo(&utf8);
+			converted = &utf8;
+		}
+#endif
+	}
 
-	log_line_prefix(&buf, edata);
+	log_line_prefix(&buf, edata, converted, &body_start);
 	appendStringInfo(&buf, "%s:  ", _(error_severity(edata->elevel)));
 
 	if (Log_error_verbosity >= PGERROR_VERBOSE)
@@ -3725,35 +3827,35 @@ send_message_to_server_log(ErrorData *edata)
 	{
 		if (edata->detail_log)
 		{
-			log_line_prefix(&buf, edata);
+			log_line_prefix(&buf, edata, converted, &body_start);
 			appendStringInfoString(&buf, _("DETAIL:  "));
 			append_with_tabs(&buf, edata->detail_log);
 			appendStringInfoChar(&buf, '\n');
 		}
 		else if (edata->detail)
 		{
-			log_line_prefix(&buf, edata);
+			log_line_prefix(&buf, edata, converted, &body_start);
 			appendStringInfoString(&buf, _("DETAIL:  "));
 			append_with_tabs(&buf, edata->detail);
 			appendStringInfoChar(&buf, '\n');
 		}
 		if (edata->hint)
 		{
-			log_line_prefix(&buf, edata);
+			log_line_prefix(&buf, edata, converted, &body_start);
 			appendStringInfoString(&buf, _("HINT:  "));
 			append_with_tabs(&buf, edata->hint);
 			appendStringInfoChar(&buf, '\n');
 		}
 		if (edata->internalquery)
 		{
-			log_line_prefix(&buf, edata);
+			log_line_prefix(&buf, edata, converted, &body_start);
 			appendStringInfoString(&buf, _("QUERY:  "));
 			append_with_tabs(&buf, edata->internalquery);
 			appendStringInfoChar(&buf, '\n');
 		}
 		if (edata->context && !edata->hide_ctx)
 		{
-			log_line_prefix(&buf, edata);
+			log_line_prefix(&buf, edata, converted, &body_start);
 			appendStringInfoString(&buf, _("CONTEXT:  "));
 			append_with_tabs(&buf, edata->context);
 			appendStringInfoChar(&buf, '\n');
@@ -3763,21 +3865,21 @@ send_message_to_server_log(ErrorData *edata)
 			/* assume no newlines in funcname or filename... */
 			if (edata->funcname && edata->filename)
 			{
-				log_line_prefix(&buf, edata);
+				log_line_prefix(&buf, edata, converted, &body_start);
 				appendStringInfo(&buf, _("LOCATION:  %s, %s:%d\n"),
 								 edata->funcname, edata->filename,
 								 edata->lineno);
 			}
 			else if (edata->filename)
 			{
-				log_line_prefix(&buf, edata);
+				log_line_prefix(&buf, edata, converted, &body_start);
 				appendStringInfo(&buf, _("LOCATION:  %s:%d\n"),
 								 edata->filename, edata->lineno);
 			}
 		}
 		if (edata->backtrace)
 		{
-			log_line_prefix(&buf, edata);
+			log_line_prefix(&buf, edata, converted, &body_start);
 			appendStringInfoString(&buf, _("BACKTRACE:  "));
 			append_with_tabs(&buf, edata->backtrace);
 			appendStringInfoChar(&buf, '\n');
@@ -3789,12 +3891,19 @@ send_message_to_server_log(ErrorData *edata)
 	 */
 	if (check_log_of_query(edata))
 	{
-		log_line_prefix(&buf, edata);
+		log_line_prefix(&buf, edata, converted, &body_start);
 		appendStringInfoString(&buf, _("STATEMENT:  "));
 		append_with_tabs(&buf, debug_query_string);
 		appendStringInfoChar(&buf, '\n');
 	}
 
+	if (converted && buf.len > body_start)
+		convert_log_segment(converted, &buf, body_start,
+							log_source_encoding());
+
+	log_text = converted ? converted->data : buf.data;
+	log_len = converted ? converted->len : buf.len;
+
 #ifdef HAVE_SYSLOG
 	/* Write to syslog, if enabled */
 	if (Log_destination & LOG_DESTINATION_SYSLOG)
@@ -3833,7 +3942,7 @@ send_message_to_server_log(ErrorData *edata)
 				break;
 		}
 
-		write_syslog(syslog_level, buf.data);
+		write_syslog(syslog_level, log_text);
 	}
 #endif							/* HAVE_SYSLOG */
 
@@ -3889,7 +3998,7 @@ send_message_to_server_log(ErrorData *edata)
 		 * Otherwise, just do a vanilla write to stderr.
 		 */
 		if (redirection_done && MyBackendType != B_LOGGER)
-			write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_STDERR);
+			write_pipe_chunks(log_text, log_len, LOG_DESTINATION_STDERR);
 #ifdef WIN32
 
 		/*
@@ -3903,14 +4012,17 @@ send_message_to_server_log(ErrorData *edata)
 			write_eventlog(edata->elevel, buf.data, buf.len);
 #endif
 		else
-			write_console(buf.data, buf.len);
+			write_console(log_text, log_len,
+						  Log_encoding == PG_UTF8 ? PG_UTF8 : GetMessageEncoding());
 	}
 
 	/* If in the syslogger process, try to write messages direct to file */
 	if (syslogger_setup_done)
-		write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_STDERR);
+		write_syslogger_file(log_text, log_len, LOG_DESTINATION_STDERR);
 
 	/* No more need of the message formatted for stderr */
+	if (converted && converted != &buf)
+		pfree(converted->data);
 	pfree(buf.data);
 }
 
@@ -3935,7 +4047,7 @@ send_message_to_server_log(ErrorData *edata)
  * rc to void to shut up the compiler.
  */
 void
-write_pipe_chunks(char *data, int len, int dest)
+write_pipe_chunks(const char *data, int len, int dest)
 {
 	PipeProtoChunk p;
 	int			fd = fileno(stderr);
@@ -4288,7 +4400,7 @@ vwrite_stderr(const char *fmt, va_list ap)
 	else
 	{
 		/* Not running as service, write to stderr */
-		write_console(errbuf, strlen(errbuf));
+		write_console(errbuf, strlen(errbuf), GetMessageEncoding());
 		fflush(stderr);
 	}
 #endif
diff --git a/src/backend/utils/error/jsonlog.c b/src/backend/utils/error/jsonlog.c
index 4a76072830..1e17bec6c6 100644
--- a/src/backend/utils/error/jsonlog.c
+++ b/src/backend/utils/error/jsonlog.c
@@ -17,6 +17,7 @@
 
 #include "access/xact.h"
 #include "libpq/libpq-be.h"
+#include "mb/pg_wchar.h"
 #include "lib/stringinfo.h"
 #include "miscadmin.h"
 #include "postmaster/syslogger.h"
@@ -32,6 +33,26 @@ static void appendJSONKeyValueFmt(StringInfo buf, const char *key,
 								  bool escape_key,
 								  const char *fmt, ...) pg_attribute_printf(4, 5);
 
+static void
+appendConvertedJSONString(StringInfo buf, const char *value, int encoding)
+{
+	LogEncodingBuffer buffer;
+
+	/* Conversion must precede JSON escaping. */
+	escape_json(buf, log_convert_text(value, -1, encoding, &buffer));
+	if (buffer.allocated)
+		pfree(buffer.allocated);
+}
+
+static inline void
+appendJSONString(StringInfo buf, const char *value, int encoding)
+{
+	if (Log_encoding == PG_UTF8)
+		appendConvertedJSONString(buf, value, encoding);
+	else
+		escape_json(buf, value);
+}
+
 /*
  * appendJSONKeyValue
  *
@@ -40,8 +61,8 @@ static void appendJSONKeyValueFmt(StringInfo buf, const char *key,
  * is dependent on the data type of the key.
  */
 static void
-appendJSONKeyValue(StringInfo buf, const char *key, const char *value,
-				   bool escape_value)
+appendJSONKeyValueEncoding(StringInfo buf, const char *key, const char *value,
+						   bool escape_value, int encoding)
 {
 	Assert(key != NULL);
 
@@ -53,12 +74,20 @@ appendJSONKeyValue(StringInfo buf, const char *key, const char *value,
 	appendStringInfoChar(buf, ':');
 
 	if (escape_value)
-		escape_json(buf, value);
+		appendJSONString(buf, value, encoding);
 	else
 		appendStringInfoString(buf, value);
 }
 
 
+static inline void
+appendJSONKeyValue(StringInfo buf, const char *key, const char *value,
+				   bool escape_value)
+{
+	appendJSONKeyValueEncoding(buf, key, value, escape_value,
+							   escape_value ? log_source_encoding() : PG_SQL_ASCII);
+}
+
 /*
  * appendJSONKeyValueFmt
  *
@@ -145,15 +174,17 @@ write_jsonlog(ErrorData *edata)
 	 */
 	escape_json(&buf, "timestamp");
 	appendStringInfoChar(&buf, ':');
-	escape_json(&buf, log_time);
+	appendJSONString(&buf, log_time, log_source_encoding());
 
 	/* username */
 	if (MyProcPort)
-		appendJSONKeyValue(&buf, "user", MyProcPort->user_name, true);
+		appendJSONKeyValueEncoding(&buf, "user", MyProcPort->user_name, true,
+								   GetDatabaseEncoding());
 
 	/* database name */
 	if (MyProcPort)
-		appendJSONKeyValue(&buf, "dbname", MyProcPort->database_name, true);
+		appendJSONKeyValueEncoding(&buf, "dbname", MyProcPort->database_name, true,
+								   GetDatabaseEncoding());
 
 	/* Process ID */
 	if (MyProcPid != 0)
diff --git a/src/backend/utils/mb/Makefile b/src/backend/utils/mb/Makefile
index a7a8359f28..dc9e05f8f7 100644
--- a/src/backend/utils/mb/Makefile
+++ b/src/backend/utils/mb/Makefile
@@ -15,6 +15,7 @@ include $(top_builddir)/src/Makefile.global
 OBJS = \
 	conv.o \
 	local_utf8.o \
+	log_encoding.o \
 	mbutils.o \
 	stringinfo_mb.o \
 	wstrcmp.o \
diff --git a/src/backend/utils/mb/log_encoding.c b/src/backend/utils/mb/log_encoding.c
new file mode 100644
index 0000000000..f75972627d
--- /dev/null
+++ b/src/backend/utils/mb/log_encoding.c
@@ -0,0 +1,170 @@
+/*-------------------------------------------------------------------------
+ *
+ * log_encoding.c
+ *	  Encoding conversion for server logs.
+ *
+ * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
+ *
+ * IDENTIFICATION
+ *	  src/backend/utils/mb/log_encoding.c
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#include "postgres.h"
+
+#include "mb/pg_wchar.h"
+#include "utils/memutils.h"
+
+StaticAssertDecl(MAX_CONVERSION_GROWTH >= 4,
+				 "log encoding escape expansion exceeds conversion growth");
+
+static const char log_conversion_truncated[] = " [truncated during log conversion]";
+
+/*
+ * Convert at most dstlen bytes, exclusive of the NUL terminator.  Preserve
+ * undecodable bytes using the same hex convention as pg_clean_ascii().
+ * Avoid SQL conversion lookup, since we may be logging outside a transaction
+ * or inside an error handler.
+ *
+ * A full destination buffer is possible on the allocation failure path.
+ * Truncate only at a character or escape boundary.
+ */
+static void
+convert_log_text(const char *src, int len, int encoding, char *dst, int dstlen,
+				 bool had_newline)
+{
+	static const char hex[] = "0123456789abcdef";
+	char	   *end = dst + dstlen;
+	bool		utf8_or_unknown = encoding == PG_UTF8 || encoding == PG_SQL_ASCII;
+
+	while (len > 0 && dst < end)
+	{
+		int			converted;
+		int			charlen;
+
+		if (utf8_or_unknown)
+		{
+			int			n = Min(len, end - dst);
+
+			converted = pg_encoding_verifymbstr(PG_UTF8, src, n);
+			if (converted > 0)
+			{
+				memcpy(dst, src, converted);
+				dst += converted;
+				src += converted;
+				len -= converted;
+				continue;
+			}
+
+			if (n < len && pg_encoding_verifymbchar(PG_UTF8, src, len) > n)
+				break;
+			charlen = 1;
+		}
+		else
+		{
+			int			n = Min(len, (end - dst) / MAX_CONVERSION_GROWTH);
+
+			if (n == 0)
+				break;
+			converted = pg_local_to_utf8((const unsigned char *) src, n,
+										 (unsigned char *) dst, encoding, true);
+			if (converted > 0)
+			{
+				dst += strlen(dst);
+				src += converted;
+				len -= converted;
+				continue;
+			}
+
+			charlen = Max(1, pg_encoding_verifymbchar(encoding, src, len));
+			if (charlen > n)
+				break;
+		}
+
+		if (charlen > (end - dst) / 4)
+			break;
+		len -= charlen;
+		while (charlen-- > 0)
+		{
+			unsigned char byte = (unsigned char) *src++;
+
+			*dst++ = '\\';
+			*dst++ = 'x';
+			*dst++ = hex[byte >> 4];
+			*dst++ = hex[byte & 0x0f];
+		}
+	}
+
+	if (len > 0)
+	{
+		memcpy(dst, log_conversion_truncated, sizeof(log_conversion_truncated) - 1);
+		dst += sizeof(log_conversion_truncated) - 1;
+		if (had_newline)
+			*dst++ = '\n';
+	}
+	*dst = '\0';
+}
+
+/*
+ * Return the original string, a string in the caller's stack buffer, or the
+ * allocated string in buffer->allocated.  Do not discard the diagnostic if the
+ * extra allocation fails, even when reporting out of memory.
+ */
+const char *
+log_convert_text(const char *text, int len, int encoding,
+				 LogEncodingBuffer *buffer)
+{
+	int			first;
+	int			limit;
+	uint64		size;
+
+	buffer->allocated = NULL;
+	if (Log_encoding != PG_UTF8)
+		return text;
+
+	if (len < 0)
+		len = strlen(text);
+	if (!PG_VALID_ENCODING(encoding))
+		encoding = PG_SQL_ASCII;
+
+	if (encoding == PG_UTF8 || encoding == PG_SQL_ASCII)
+		first = pg_encoding_verifymbstr(PG_UTF8, text, len);
+	else
+	{
+		for (first = 0; first < len && text[first] &&
+			 !IS_HIGHBIT_SET(text[first]); first++)
+			;
+	}
+	if (first == len)
+		return text;
+
+	/*
+	 * Skip the heap for short messages.  Leave space for an escape per byte
+	 * and for the truncation notice on the stack-buffer fallback path.
+	 */
+	size = (uint64) (len - first) * MAX_CONVERSION_GROWTH + first + 1;
+	if (size > sizeof(buffer->data) && size <= MaxAllocSize &&
+		CurrentMemoryContext != NULL)
+		buffer->allocated = palloc_extended(size, MCXT_ALLOC_NO_OOM);
+
+	if (size <= sizeof(buffer->data) || buffer->allocated)
+	{
+		char	   *dst = buffer->allocated ? buffer->allocated : buffer->data;
+
+		memcpy(dst, text, first);
+		convert_log_text(text +first, len - first, encoding, dst + first,
+						 size - first - 1, false);
+		return dst;
+	}
+
+	/* Reserve space for the truncation notice, a newline and the NUL. */
+	limit = sizeof(buffer->data) - sizeof(log_conversion_truncated) - 1;
+	first = Min(first, limit);
+	if (encoding == PG_UTF8 || encoding == PG_SQL_ASCII)
+		first = pg_encoding_mbcliplen(PG_UTF8, text, first, first);
+	memcpy(buffer->data, text, first);
+	convert_log_text(text +first, len - first, encoding, buffer->data + first,
+					 limit - first, text[len - 1] == '\n');
+	return buffer->data;
+}
diff --git a/src/backend/utils/mb/mbutils.c b/src/backend/utils/mb/mbutils.c
index bdfdd9eeac..96d600b878 100644
--- a/src/backend/utils/mb/mbutils.c
+++ b/src/backend/utils/mb/mbutils.c
@@ -81,6 +81,7 @@ static FmgrInfo *Utf8ToServerConvProc = NULL;
  */
 static const pg_enc2name *ClientEncoding = &pg_enc2name_tbl[PG_SQL_ASCII];
 static const pg_enc2name *DatabaseEncoding = &pg_enc2name_tbl[PG_SQL_ASCII];
+static bool DatabaseEncodingSet;
 static const pg_enc2name *MessageEncoding = &pg_enc2name_tbl[PG_SQL_ASCII];
 
 /*
@@ -1293,6 +1294,7 @@ SetDatabaseEncoding(int encoding)
 		elog(ERROR, "invalid database encoding: %d", encoding);
 
 	DatabaseEncoding = &pg_enc2name_tbl[encoding];
+	DatabaseEncodingSet = true;
 	Assert(DatabaseEncoding->encoding == encoding);
 }
 
@@ -1391,6 +1393,17 @@ GetDatabaseEncoding(void)
 	return DatabaseEncoding->encoding;
 }
 
+/*
+ * Before CheckMyDatabase sets the database encoding, translated diagnostics
+ * use the process locale.  MyDatabaseId can already be valid at this point.
+ * Once attached, SQL_ASCII means that the bytes have no declared encoding.
+ */
+int
+log_source_encoding(void)
+{
+	return DatabaseEncodingSet ? DatabaseEncoding->encoding : MessageEncoding->encoding;
+}
+
 const char *
 GetDatabaseEncodingName(void)
 {
@@ -1904,16 +1917,20 @@ report_untranslatable_char(int src_encoding, int dest_encoding,
 
 
 #ifdef WIN32
+WCHAR *
+pgwin32_message_to_UTF16(const char *str, int len, int *utf16len)
+{
+	return pgwin32_to_UTF16(str, len, utf16len, GetMessageEncoding());
+}
+
 /*
- * Convert from MessageEncoding to a palloc'ed, null-terminated utf16
+ * Convert from the given encoding to a palloc'ed, null-terminated utf16
  * string. The character length is also passed to utf16len if not
- * null. Returns NULL iff failed. Before MessageEncoding initialization, "str"
- * should be ASCII-only; this will function as though MessageEncoding is UTF8.
+ * null. Returns NULL on failure or if the input encoding is SQL_ASCII.
  */
 WCHAR *
-pgwin32_message_to_UTF16(const char *str, int len, int *utf16len)
+pgwin32_to_UTF16(const char *str, int len, int *utf16len, int msgenc)
 {
-	int			msgenc = GetMessageEncoding();
 	WCHAR	   *utf16;
 	int			dstlen;
 	UINT		codepage;
@@ -1931,7 +1948,11 @@ pgwin32_message_to_UTF16(const char *str, int len, int *utf16len)
 	 */
 	if (codepage != 0)
 	{
-		utf16 = palloc_array(WCHAR, len + 1);
+		if ((Size) len >= MaxAllocSize / sizeof(WCHAR))
+			return NULL;
+		utf16 = palloc_array_extended(WCHAR, len + 1, MCXT_ALLOC_NO_OOM);
+		if (utf16 == NULL)
+			return NULL;
 		dstlen = MultiByteToWideChar(codepage, 0, str, len, utf16, len);
 		utf16[dstlen] = (WCHAR) 0;
 	}
diff --git a/src/backend/utils/mb/meson.build b/src/backend/utils/mb/meson.build
index a86ab549dd..8c0f487bf7 100644
--- a/src/backend/utils/mb/meson.build
+++ b/src/backend/utils/mb/meson.build
@@ -3,6 +3,7 @@
 backend_sources += files(
   'conv.c',
   'local_utf8.c',
+  'log_encoding.c',
   'mbutils.c',
   'stringinfo_mb.c',
   'wstrcmp.c',
diff --git a/src/backend/utils/misc/guc_parameters.dat b/src/backend/utils/misc/guc_parameters.dat
index 8a8f1cca09..e6cf1e4b74 100644
--- a/src/backend/utils/misc/guc_parameters.dat
+++ b/src/backend/utils/misc/guc_parameters.dat
@@ -1707,6 +1707,13 @@
   boot_val => 'false',
 },
 
+{ name => 'log_encoding', type => 'enum', context => 'PGC_POSTMASTER', group => 'LOGGING_WHERE',
+  short_desc => 'Sets the encoding of server log messages.',
+  variable => 'Log_encoding',
+  boot_val => 'PG_SQL_ASCII',
+  options => 'log_encoding_options',
+},
+
 { name => 'log_error_verbosity', type => 'enum', context => 'PGC_SUSET', group => 'LOGGING_WHAT',
   short_desc => 'Sets the verbosity of logged messages.',
   variable => 'Log_error_verbosity',
diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c
index a05fc356fc..737b946742 100644
--- a/src/backend/utils/misc/guc_tables.c
+++ b/src/backend/utils/misc/guc_tables.c
@@ -195,6 +195,13 @@ static const struct config_enum_entry icu_validation_level_options[] = {
 StaticAssertDecl(lengthof(intervalstyle_options) == (INTSTYLE_ISO_8601 + 2),
 				 "array length mismatch");
 
+static const struct config_enum_entry log_encoding_options[] = {
+	{"off", PG_SQL_ASCII, false},
+	{"utf8", PG_UTF8, false},
+	{"utf-8", PG_UTF8, true},
+	{NULL, 0, false}
+};
+
 static const struct config_enum_entry log_error_verbosity_options[] = {
 	{"terse", PGERROR_TERSE, false},
 	{"default", PGERROR_DEFAULT, false},
diff --git a/src/backend/utils/misc/postgresql.conf.sample b/src/backend/utils/misc/postgresql.conf.sample
index b492b3af06..271925b390 100644
--- a/src/backend/utils/misc/postgresql.conf.sample
+++ b/src/backend/utils/misc/postgresql.conf.sample
@@ -507,6 +507,7 @@
 
 # - Where to Log -
 
+#log_encoding = off                     # off or utf8 (change requires restart)
 #log_destination = 'stderr'             # Valid values are combinations of
                                         # stderr, csvlog, jsonlog, syslog, and
                                         # eventlog, depending on platform.
diff --git a/src/include/mb/pg_wchar.h b/src/include/mb/pg_wchar.h
index fc954a94d7..66283863de 100644
--- a/src/include/mb/pg_wchar.h
+++ b/src/include/mb/pg_wchar.h
@@ -704,6 +704,7 @@ extern int	local2local(const unsigned char *l, unsigned char *p, int len,
 
 #ifdef WIN32
 extern WCHAR *pgwin32_message_to_UTF16(const char *str, int len, int *utf16len);
+extern WCHAR *pgwin32_to_UTF16(const char *str, int len, int *utf16len, int encoding);
 #endif
 
 #endif							/* PG_WCHAR_H */
diff --git a/src/include/utils/elog.h b/src/include/utils/elog.h
index bc38d154ed..0224b38723 100644
--- a/src/include/utils/elog.h
+++ b/src/include/utils/elog.h
@@ -497,6 +497,7 @@ typedef enum
 extern PGDLLIMPORT int Log_error_verbosity;
 extern PGDLLIMPORT char *Log_line_prefix;
 extern PGDLLIMPORT int Log_destination;
+extern PGDLLIMPORT int Log_encoding;
 extern PGDLLIMPORT char *Log_destination_string;
 extern PGDLLIMPORT bool syslog_sequence_numbers;
 extern PGDLLIMPORT bool syslog_split_messages;
@@ -522,7 +523,16 @@ extern char *get_formatted_log_time(void);
 extern const char *get_backend_type_for_log(void);
 extern bool check_log_of_query(ErrorData *edata);
 extern const char *error_severity(int elevel);
-extern void write_pipe_chunks(char *data, int len, int dest);
+typedef struct LogEncodingBuffer
+{
+	char	   *allocated;
+	char		data[1024];
+} LogEncodingBuffer;
+
+extern const char *log_convert_text(const char *text, int len, int encoding,
+									LogEncodingBuffer *buffer);
+extern int	log_source_encoding(void);
+extern void write_pipe_chunks(const char *data, int len, int dest);
 
 /* Destination-specific functions */
 extern void write_csvlog(ErrorData *edata);
diff --git a/src/test/modules/test_misc/meson.build b/src/test/modules/test_misc/meson.build
index 5225aa280c..609999dc0f 100644
--- a/src/test/modules/test_misc/meson.build
+++ b/src/test/modules/test_misc/meson.build
@@ -25,6 +25,7 @@ tests += {
       't/014_log_statement_max_length.pl',
       't/015_temp_schema_exit_deferrable.pl',
       't/016_heap_scan_stream.pl',
+      't/017_log_encoding.pl',
     ],
     # The injection points are cluster-wide, so disable installcheck
     'runningcheck': false,
diff --git a/src/test/modules/test_misc/t/017_log_encoding.pl b/src/test/modules/test_misc/t/017_log_encoding.pl
new file mode 100644
index 0000000000..1cd950bb26
--- /dev/null
+++ b/src/test/modules/test_misc/t/017_log_encoding.pl
@@ -0,0 +1,135 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+use strict;
+use warnings FATAL => 'all';
+
+use Encode   qw(encode decode FB_CROAK LEAVE_SRC);
+use JSON::PP qw(decode_json);
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+my $node = PostgreSQL::Test::Cluster->new('log_encoding');
+$node->init(extra => [ '--locale=C', '--encoding=UTF8' ]);
+$node->append_conf(
+	'postgresql.conf', q(
+logging_collector = on
+log_destination = 'stderr,csvlog,jsonlog'
+log_filename = 'default.log'
+log_rotation_age = 0
+lc_messages = 'C'
+));
+$node->start;
+is($node->safe_psql('postgres', 'SHOW log_encoding'),
+	'off', 'log transcoding is disabled by default');
+$node->safe_psql('postgres',
+	q(CREATE DATABASE legacy ENCODING 'WIN1251' TEMPLATE template0));
+$node->safe_psql('postgres',
+	q(CREATE DATABASE raw_bytes ENCODING 'SQL_ASCII' TEMPLATE template0));
+
+my $sql = q(DO $$ BEGIN RAISE WARNING 'log_encoding_test %',
+  U&'\041F\0440\0438\0432\0435\0442' USING DETAIL = U&'\0414'; END $$);
+$node->safe_psql('legacy', $sql);
+$node->stop;
+my $expected = "log_encoding_test \x{41f}\x{440}\x{438}\x{432}\x{435}\x{442}";
+my $default_log = slurp_file($node->data_dir . '/log/default.log');
+my $legacy_message = encode('cp1251', $expected);
+like($default_log, qr/\Q$legacy_message\E/,
+	'the default log retains the database encoding');
+
+my $prefix = "prefix \x{416}";
+$node->append_conf(
+	'postgresql.conf', q(
+log_filename = 'encoding.log'
+log_encoding = utf8
+));
+$node->append_conf('postgresql.conf',
+	encode('UTF-8', "log_line_prefix = '$prefix %% %d: '"));
+$node->start;
+is($node->safe_psql('postgres', 'SHOW log_encoding'),
+	'utf8', 'server accepts UTF8 log encoding');
+
+$node->safe_psql('postgres', $sql);
+$node->safe_psql('legacy', $sql);
+$node->safe_psql('postgres',
+	q(CREATE DATABASE japanese ENCODING 'EUC_JIS_2004' TEMPLATE template0));
+# EUC_JIS_2004 0xa4f7 maps to both U+304B and U+309A.
+$node->safe_psql(
+	'japanese', q(DO $$ BEGIN
+  RAISE WARNING 'combined %', convert_from(decode('a4f7', 'hex'), 'EUC_JIS_2004');
+  END $$));
+$node->safe_psql(
+	'legacy', q(DO $$ BEGIN
+  RAISE WARNING '%', 'long "' || repeat(U&'\0416', 1500) || '" tail';
+  END $$));
+$node->safe_psql(
+	'raw_bytes', q(DO $$ BEGIN RAISE WARNING 'log_encoding_bytes %',
+  convert_from(decode('ff', 'hex'), 'SQL_ASCII'); END $$));
+
+$node->safe_psql(
+	'raw_bytes', q(DO $$ BEGIN RAISE WARNING '%',
+  repeat('A', 1003) || convert_from(decode('ff', 'hex'), 'SQL_ASCII') || 'END';
+  END $$));
+
+$node->psql(
+	'legacy',
+	q(BEGIN; SELECT 1/0; SELECT U&'\0410'; ROLLBACK;),
+	on_error_stop => 0);
+$node->connect_fails("user=log_encoding_missing_role",
+	'log an authentication failure before selecting a database encoding');
+$node->stop;
+
+my $long_message = 'long "' . ("\x{416}" x 1500) . '" tail';
+my $combined = "combined \x{304b}\x{309a}";
+for my $extension (qw(log csv json))
+{
+	my $bytes = slurp_file($node->data_dir . "/log/encoding.$extension");
+	my $text = eval { decode('UTF-8', $bytes, FB_CROAK | LEAVE_SRC) };
+	ok(defined $text, "$extension log consists of valid UTF-8");
+	my @matches = $text =~ /\Q$expected\E/g;
+	is(scalar @matches, 2, "$extension converts both database encodings");
+	like($text, qr/\Q$combined\E/, "$extension retains combined characters");
+	like($text, qr/log_encoding_missing_role/,
+		"$extension records failed login");
+	if ($extension eq 'log')
+	{
+		like(
+			$text,
+			qr/\Q$prefix % legacy: WARNING:  $expected\E/,
+			'a UTF-8 prefix survives logging from a WIN1251 database');
+		like(
+			$text,
+			qr/\Q$prefix % legacy: DETAIL:  \E\x{414}/,
+			'the next prefix and its detail are converted independently');
+	}
+	if ($extension eq 'json')
+	{
+		my @records = map { decode_json($_) } split /\n/, $bytes;
+		my @messages = map { $_->{message} // '' } @records;
+		ok( (scalar grep { $_ eq $long_message } @messages),
+			'JSON preserves a long converted field including embedded quotes'
+		);
+		ok((scalar grep { ($_->{state_code} // '') eq '25P02' } @records),
+			'logs an error while the transaction is aborted');
+		ok( (scalar grep { $_ eq (('A' x 1003) . '\xffEND') } @messages),
+			'escape at the end of a full stack buffer preserves the whole message'
+		);
+		ok( (scalar grep { $_ eq 'log_encoding_bytes \xff' } @messages),
+			'JSON preserves the invalid byte as a literal hexadecimal escape'
+		);
+	}
+	else
+	{
+		my $long_field = $long_message;
+		$long_field =~ s/"/""/g if $extension eq 'csv';
+		like($text, qr/\Q$long_field\E/,
+			"$extension preserves a long converted field including embedded quotes"
+		);
+		like(
+			$text,
+			qr/log_encoding_bytes \\xff/,
+			"$extension preserves the invalid byte as a hexadecimal escape");
+	}
+}
+
+done_testing();
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index f10eb46926..5bfe2487cd 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -1651,6 +1651,7 @@ LockTupleMode
 LockViewRecurse_context
 LockWaitPolicy
 LockingClause
+LogEncodingBuffer
 LogOpts
 LogStmtLevel
 LogicalDecodeBeginCB
