diff --git a/contrib/postgres_fdw/connection.c b/contrib/postgres_fdw/connection.c
index 705f60a3ae..ea8b072cd2 100644
--- a/contrib/postgres_fdw/connection.c
+++ b/contrib/postgres_fdw/connection.c
@@ -348,7 +348,9 @@ connect_pg_server(ForeignServer *server, UserMapping *user)
 	{
 		const char **keywords;
 		const char **values;
+		const char **buf;
 		int			n;
+		int			i;
 
 		/*
 		 * Construct connection params from generic options of ForeignServer
@@ -360,6 +362,7 @@ connect_pg_server(ForeignServer *server, UserMapping *user)
 		n = list_length(server->options) + list_length(user->options) + 4;
 		keywords = (const char **) palloc(n * sizeof(char *));
 		values = (const char **) palloc(n * sizeof(char *));
+		buf = (const char **) palloc(sizeof(char *));
 
 		n = 0;
 		n += ExtractConnectionOptions(server->options,
@@ -383,6 +386,25 @@ connect_pg_server(ForeignServer *server, UserMapping *user)
 			n++;
 		}
 
+		/*
+		 * Search application_name and replace it if found.
+		 *
+		 * We search paramters from the end because the later
+		 * one have higher priority.  See also the above comment.
+		 */
+		for (i = n - 1; i >= 0; i--)
+		{
+			if (strcmp(keywords[i], "application_name") == 0)
+			{
+				parse_pgfdw_appname(buf, values[i]);
+				/*
+				 * Note that appname may becomes an empty string
+				 * if an input string has wrong format.
+				 */
+				values[i] = *buf;
+			}
+		}
+
 		/* Use "postgres_fdw" as fallback_application_name */
 		keywords[n] = "fallback_application_name";
 		values[n] = "postgres_fdw";
@@ -454,6 +476,7 @@ connect_pg_server(ForeignServer *server, UserMapping *user)
 
 		pfree(keywords);
 		pfree(values);
+		pfree(buf);
 	}
 	PG_CATCH();
 	{
diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index c7b7db8065..aa9673e398 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -10761,3 +10761,33 @@ ERROR:  invalid value for integer option "fetch_size": 100$%$#$#
 CREATE FOREIGN TABLE inv_bsz (c1 int )
 	SERVER loopback OPTIONS (batch_size '100$%$#$#');
 ERROR:  invalid value for integer option "batch_size": 100$%$#$#
+-- ===================================================================
+-- test postgres_fdw.application_name GUC
+-- ===================================================================
+SET debug_discard_caches TO 0;
+-- Some escapes can be used for this GUC.
+SET postgres_fdw.application_name TO '%a%u%d%p%%';
+-- All escape candidates depend on the runtime environment
+-- and it causes some fails for this tests.
+-- Hence we just count number of rows here. It returns a row if works well.
+SELECT 1 FROM postgres_fdw_disconnect_all();
+ ?column? 
+----------
+        1
+(1 row)
+
+SELECT 1 FROM ft6 LIMIT 1;
+ ?column? 
+----------
+        1
+(1 row)
+
+SELECT COUNT(*) FROM pg_stat_activity WHERE application_name = current_setting('application_name') || current_user || current_database() || pg_backend_pid() || '%';
+ count 
+-------
+     1
+(1 row)
+
+--Clean up
+RESET postgres_fdw.application_name;
+RESET debug_discard_caches;
diff --git a/contrib/postgres_fdw/option.c b/contrib/postgres_fdw/option.c
index 5bb1af4084..67f4172d61 100644
--- a/contrib/postgres_fdw/option.c
+++ b/contrib/postgres_fdw/option.c
@@ -20,9 +20,9 @@
 #include "commands/extension.h"
 #include "postgres_fdw.h"
 #include "utils/builtins.h"
+#include "utils/elog.h"
 #include "utils/guc.h"
 #include "utils/varlena.h"
-
 /*
  * Describes the valid options for objects that this wrapper uses.
  */
@@ -443,6 +443,15 @@ ExtractExtensionList(const char *extensionsString, bool warnOnMissing)
 	return extensionOids;
 }
 
+/*
+ * Wrapper function for process_format_string
+ */
+void
+parse_pgfdw_appname(const char **out, const char *name)
+{
+	process_format_string(out, name, NULL, 0, "audp%");
+}
+
 /*
  * Module load callback
  */
diff --git a/contrib/postgres_fdw/postgres_fdw.h b/contrib/postgres_fdw/postgres_fdw.h
index 90b72e9ec5..2909a5e24f 100644
--- a/contrib/postgres_fdw/postgres_fdw.h
+++ b/contrib/postgres_fdw/postgres_fdw.h
@@ -158,6 +158,7 @@ extern int	ExtractConnectionOptions(List *defelems,
 									 const char **values);
 extern List *ExtractExtensionList(const char *extensionsString,
 								  bool warnOnMissing);
+extern void parse_pgfdw_appname(const char **out, const char *name);
 extern char *pgfdw_application_name;
 
 /* in deparse.c */
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index 38f4a7837f..c6c10996a0 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -3422,3 +3422,20 @@ CREATE FOREIGN TABLE inv_fsz (c1 int )
 -- Invalid batch_size option
 CREATE FOREIGN TABLE inv_bsz (c1 int )
 	SERVER loopback OPTIONS (batch_size '100$%$#$#');
+
+-- ===================================================================
+-- test postgres_fdw.application_name GUC
+-- ===================================================================
+SET debug_discard_caches TO 0;
+-- Some escapes can be used for this GUC.
+SET postgres_fdw.application_name TO '%a%u%d%p%%';
+-- All escape candidates depend on the runtime environment
+-- and it causes some fails for this tests.
+-- Hence we just count number of rows here. It returns a row if works well.
+SELECT 1 FROM postgres_fdw_disconnect_all();
+SELECT 1 FROM ft6 LIMIT 1;
+SELECT COUNT(*) FROM pg_stat_activity WHERE application_name = current_setting('application_name') || current_user || current_database() || pg_backend_pid() || '%';
+
+--Clean up
+RESET postgres_fdw.application_name;
+RESET debug_discard_caches;
diff --git a/doc/src/sgml/postgres-fdw.sgml b/doc/src/sgml/postgres-fdw.sgml
index bf95da9721..141f3ce5fa 100644
--- a/doc/src/sgml/postgres-fdw.sgml
+++ b/doc/src/sgml/postgres-fdw.sgml
@@ -180,6 +180,10 @@ OPTIONS (ADD password_required 'false');
     relationship granted by authentication modes like <literal>peer</literal>
     or <literal>ident</literal> authentication.
    </para>
+   <para>
+    You can use escape sequences for <literal>application_name</literal> even if
+    it is set as a connection option. Please refer the later section.
+   </para>
   </sect3>
 
   <sect3>
@@ -909,7 +913,7 @@ postgres=# SELECT postgres_fdw_disconnect_all();
   <title>Configuration Parameters</title>
 
   <variablelist>
-   <varlistentry>
+   <varlistentry id="guc-pgfdw-application-name" xreflabel="pgfdw_application_name">
     <term>
      <varname>postgres_fdw.application_name</varname> (<type>string</type>)
      <indexterm>
@@ -925,6 +929,53 @@ postgres=# SELECT postgres_fdw_disconnect_all();
       Note that change of this parameter doesn't affect any existing
       connections until they are re-established.
      </para>
+
+     <para>
+      Same as <xref linkend="guc-log-line-prefix"/>, this is a
+      <function>printf</function>-style string. Accepted escapes are
+      bit different from <xref linkend="guc-log-line-prefix"/>,
+      but padding can be used like as it.
+     </para>
+
+     <informaltable>
+      <tgroup cols="2">
+       <thead>
+        <row>
+         <entry>Escape</entry>
+         <entry>Effect</entry>
+        </row>
+       </thead>
+       <tbody>
+        <row>
+         <entry><literal>%a</literal></entry>
+         <entry>Application name</entry>
+        </row>
+        <row>
+         <entry><literal>%u</literal></entry>
+         <entry>Local user name</entry>
+        </row>
+        <row>
+         <entry><literal>%d</literal></entry>
+         <entry>Local database name</entry>
+        </row>
+        <row>
+         <entry><literal>%p</literal></entry>
+         <entry>Local backend process ID</entry>
+        </row>
+        <row>
+         <entry><literal>%%</literal></entry>
+         <entry>Liteal %</entry>
+        </row>
+       </tbody>
+      </tgroup>
+     </informaltable>
+
+     <para>
+     Note that if embedded strings have Non-ASCII,
+     these characters will be replaced with the question marks (<literal>?</literal>).
+     This limitation is caused by <literal>application_name</literal>.
+     </para>
+
     </listitem>
    </varlistentry>
   </variablelist>
diff --git a/src/backend/utils/error/elog.c b/src/backend/utils/error/elog.c
index 2af87ee3bd..657db0728a 100644
--- a/src/backend/utils/error/elog.c
+++ b/src/backend/utils/error/elog.c
@@ -177,7 +177,7 @@ static void set_errdata_field(MemoryContextData *cxt, char **ptr, const char *st
 static void write_console(const char *line, int len);
 static void setup_formatted_log_time(void);
 static void setup_formatted_start_time(void);
-static const char *process_log_prefix_padding(const char *p, int *padding);
+static int parse_padding(const char *nptr, char **endptr);
 static void log_line_prefix(StringInfo buf, ErrorData *edata);
 static void write_csvlog(ErrorData *edata);
 static void send_message_to_server_log(ErrorData *edata);
@@ -2338,43 +2338,12 @@ setup_formatted_start_time(void)
 				pg_localtime(&stamp_time, log_timezone));
 }
 
-/*
- * process_log_prefix_padding --- helper function for processing the format
- * string in log_line_prefix
- *
- * Note: This function returns NULL if it finds something which
- * it deems invalid in the format string.
- */
-static const char *
-process_log_prefix_padding(const char *p, int *ppadding)
-{
-	int			paddingsign = 1;
-	int			padding = 0;
-
-	if (*p == '-')
-	{
-		p++;
-
-		if (*p == '\0')			/* Did the buf end in %- ? */
-			return NULL;
-		paddingsign = -1;
-	}
-
-	/* generate an int version of the numerical string */
-	while (*p >= '0' && *p <= '9')
-		padding = padding * 10 + (*p++ - '0');
-
-	/* format is invalid if it ends with the padding number */
-	if (*p == '\0')
-		return NULL;
-
-	padding *= paddingsign;
-	*ppadding = padding;
-	return p;
-}
-
 /*
  * Format tag info for log lines; append to the provided buffer.
+ * 
+ * This is also the wrapper function for process_format_string(),
+ * but this counts log_line_number.
+ * 
  */
 static void
 log_line_prefix(StringInfo buf, ErrorData *edata)
@@ -2384,8 +2353,9 @@ log_line_prefix(StringInfo buf, ErrorData *edata)
 
 	/* has counter been reset in current process? */
 	static int	log_my_pid = 0;
-	int			padding;
-	const char *p;
+
+	/* receiver for parsing function */
+	const char **out = (const char **) palloc0(sizeof(char *));
 
 	/*
 	 * This is one of the few places where we'd rather not inherit a static
@@ -2404,7 +2374,41 @@ log_line_prefix(StringInfo buf, ErrorData *edata)
 	if (Log_line_prefix == NULL)
 		return;					/* in case guc hasn't run yet */
 
-	for (p = Log_line_prefix; *p != '\0'; p++)
+	process_format_string(out, Log_line_prefix, edata, log_line_number, NULL);
+
+	/*
+	 * Reset buf once and append again, because the parsing function
+	 * cannot accept StringInfo.
+	 */
+	resetStringInfo(buf);
+	if (*out != NULL)
+		appendStringInfoString(buf, *out);
+	else
+		appendStringInfoChar(buf, '\0');
+
+	pfree(out);
+}
+
+/*
+ * process_format_string - parse string and translate escapes
+ * 
+ * This function parses an input string
+ * and replaces escape sequences if possible.
+ * escape_chars specifies the allowed escapes, and accept all if NULL is set.
+ * Note: StringInfo datatype cannot be accepted
+ * because elog.h should not include postgres-original header file.
+ */
+void
+process_format_string(const char** out, const char *input, ErrorData *edata, long log_line_number, const char *escape_chars)
+{
+	int padding;
+	const char *p;
+	StringInfo buf = makeStringInfo();
+
+	if (!input)
+		goto cleanup;
+
+	for (p = input; *p != '\0'; p++)
 	{
 		if (*p != '%')
 		{
@@ -2426,9 +2430,7 @@ log_line_prefix(StringInfo buf, ErrorData *edata)
 
 
 		/*
-		 * Process any formatting which may exist after the '%'.  Note that
-		 * process_log_prefix_padding moves p past the padding number if it
-		 * exists.
+		 * Process any formatting which may exist after the '%'.
 		 *
 		 * Note: Since only '-', '0' to '9' are valid formatting characters we
 		 * can do a quick check here to pre-check for formatting. If the char
@@ -2441,8 +2443,17 @@ log_line_prefix(StringInfo buf, ErrorData *edata)
 		 */
 		if (*p > '9')
 			padding = 0;
-		else if ((p = process_log_prefix_padding(p, &padding)) == NULL)
-			break;
+		else
+		{
+			char *endptr = NULL;
+			padding = parse_padding(p, &endptr);
+			if (!endptr|| *endptr == '\0')
+				break;
+			p = endptr;
+		}
+
+		if (escape_chars && !strchr(escape_chars, *p))
+			continue;
 
 		/* process the option */
 		switch (*p)
@@ -2709,6 +2720,7 @@ log_line_prefix(StringInfo buf, ErrorData *edata)
 					appendStringInfo(buf, "%u", GetTopTransactionIdIfAny());
 				break;
 			case 'e':
+				Assert(edata);
 				if (padding != 0)
 					appendStringInfo(buf, "%*s", padding, unpack_sql_state(edata->sqlerrcode));
 				else
@@ -2727,6 +2739,58 @@ log_line_prefix(StringInfo buf, ErrorData *edata)
 				break;
 		}
 	}
+
+	*out = buf->data;
+cleanup:
+	pfree(buf);
+}
+
+/*
+ * parse_padding --- helper function for process_format_string()
+ *
+ * This converts initial part of the string and returns
+ * the result of the convertion.
+ *
+ * This function is very similar to strtoint(),
+ * but this follows the printf-format more precisely than that.
+ */
+static int
+parse_padding(const char *nptr, char **endptr)
+{
+	int			paddingsign = 1;
+	int			padding = 0;
+	const char*	p = nptr;
+
+	if (*p == '-')
+	{
+		p++;
+
+		if (*p == '\0')			/* Did the buf end in %- ? */
+		{
+			if (endptr)
+				*endptr = (char *)p;
+			return 0;
+		}
+		paddingsign = -1;
+	}
+
+	/* generate an int version of the numerical string */
+	while (*p >= '0' && *p <= '9')
+		padding = padding * 10 + (*p++ - '0');
+
+	/* format is invalid if it ends with the padding number */
+	if (*p == '\0')
+	{
+		if (endptr)
+			*endptr = '\0';
+		return 0;
+	}
+
+	padding *= paddingsign;
+
+	if (endptr)
+		*endptr = (char *)p;
+	return padding;
 }
 
 /*
diff --git a/src/include/utils/elog.h b/src/include/utils/elog.h
index f53607e12e..a6b24688da 100644
--- a/src/include/utils/elog.h
+++ b/src/include/utils/elog.h
@@ -446,6 +446,7 @@ extern bool in_error_recursion_trouble(void);
 extern void set_syslog_parameters(const char *ident, int facility);
 #endif
 
+extern void process_format_string(const char **out, const char *input, ErrorData *edata, long log_line_number, const char *escape_chars);
 /*
  * Write errors to stderr (or by equal means when stderr is
  * not available). Used before ereport/elog can be used
