Unified logging system for command-line programs
authorPeter Eisentraut <peter@eisentraut.org>
Mon, 1 Apr 2019 12:24:37 +0000 (14:24 +0200)
committerPeter Eisentraut <peter@eisentraut.org>
Mon, 1 Apr 2019 18:01:35 +0000 (20:01 +0200)
This unifies the various ad hoc logging (message printing, error
printing) systems used throughout the command-line programs.

Features:

- Program name is automatically prefixed.

- Message string does not end with newline.  This removes a common
  source of inconsistencies and omissions.

- Additionally, a final newline is automatically stripped, simplifying
  use of PQerrorMessage() etc., another common source of mistakes.

- I converted error message strings to use %m where possible.

- As a result of the above several points, more translatable message
  strings can be shared between different components and between
  frontends and backend, without gratuitous punctuation or whitespace
  differences.

- There is support for setting a "log level".  This is not meant to be
  user-facing, but can be used internally to implement debug or
  verbose modes.

- Lazy argument evaluation, so no significant overhead if logging at
  some level is disabled.

- Some color in the messages, similar to gcc and clang.  Set
  PG_COLOR=auto to try it out.  Some colors are predefined, but can be
  customized by setting PG_COLORS.

- Common files (common/, fe_utils/, etc.) can handle logging much more
  simply by just using one API without worrying too much about the
  context of the calling program, requiring callbacks, or having to
  pass "progname" around everywhere.

- Some programs called setvbuf() to make sure that stderr is
  unbuffered, even on Windows.  But not all programs did that.  This
  is now done centrally.

Soft goals:

- Reduces vertical space use and visual complexity of error reporting
  in the source code.

- Encourages more deliberate classification of messages.  For example,
  in some cases it wasn't clear without analyzing the surrounding code
  whether a message was meant as an error or just an info.

- Concepts and terms are vaguely aligned with popular logging
  frameworks such as log4j and Python logging.

This is all just about printing stuff out.  Nothing affects program
flow (e.g., fatal exits).  The uses are just too varied to do that.
Some existing code had wrappers that do some kind of print-and-exit,
and I adapted those.

I tried to keep the output mostly the same, but there is a lot of
historical baggage to unwind and special cases to consider, and I
might not always have succeeded.  One significant change is that
pg_rewind used to write all error messages to stdout.  That is now
changed to stderr.

Reviewed-by: Donald Dong <xdong@csumb.edu>
Reviewed-by: Arthur Zakirov <a.zakirov@postgrespro.ru>
Discussion: https://www.postgresql.org/message-id/flat/6a609b43-4f57-7348-6480-bd022f924310@2ndquadrant.com

132 files changed:
doc/src/sgml/ref/clusterdb.sgml
doc/src/sgml/ref/createdb.sgml
doc/src/sgml/ref/createuser.sgml
doc/src/sgml/ref/dropdb.sgml
doc/src/sgml/ref/dropuser.sgml
doc/src/sgml/ref/initdb.sgml
doc/src/sgml/ref/pg_basebackup.sgml
doc/src/sgml/ref/pg_checksums.sgml
doc/src/sgml/ref/pg_controldata.sgml
doc/src/sgml/ref/pg_dump.sgml
doc/src/sgml/ref/pg_dumpall.sgml
doc/src/sgml/ref/pg_isready.sgml
doc/src/sgml/ref/pg_receivewal.sgml
doc/src/sgml/ref/pg_recvlogical.sgml
doc/src/sgml/ref/pg_resetwal.sgml
doc/src/sgml/ref/pg_restore.sgml
doc/src/sgml/ref/pg_rewind.sgml
doc/src/sgml/ref/pg_waldump.sgml
doc/src/sgml/ref/psql-ref.sgml
doc/src/sgml/ref/reindexdb.sgml
doc/src/sgml/ref/vacuumdb.sgml
src/backend/access/transam/xlog.c
src/backend/utils/misc/pg_controldata.c
src/bin/initdb/initdb.c
src/bin/initdb/nls.mk
src/bin/pg_archivecleanup/Makefile
src/bin/pg_archivecleanup/nls.mk
src/bin/pg_archivecleanup/pg_archivecleanup.c
src/bin/pg_basebackup/nls.mk
src/bin/pg_basebackup/pg_basebackup.c
src/bin/pg_basebackup/pg_receivewal.c
src/bin/pg_basebackup/pg_recvlogical.c
src/bin/pg_basebackup/receivelog.c
src/bin/pg_basebackup/streamutil.c
src/bin/pg_basebackup/walmethods.c
src/bin/pg_checksums/Makefile
src/bin/pg_checksums/nls.mk
src/bin/pg_checksums/pg_checksums.c
src/bin/pg_controldata/Makefile
src/bin/pg_controldata/pg_controldata.c
src/bin/pg_ctl/Makefile
src/bin/pg_ctl/pg_ctl.c
src/bin/pg_dump/common.c
src/bin/pg_dump/compress_io.c
src/bin/pg_dump/nls.mk
src/bin/pg_dump/parallel.c
src/bin/pg_dump/pg_backup_archiver.c
src/bin/pg_dump/pg_backup_archiver.h
src/bin/pg_dump/pg_backup_custom.c
src/bin/pg_dump/pg_backup_db.c
src/bin/pg_dump/pg_backup_directory.c
src/bin/pg_dump/pg_backup_null.c
src/bin/pg_dump/pg_backup_tar.c
src/bin/pg_dump/pg_backup_utils.c
src/bin/pg_dump/pg_backup_utils.h
src/bin/pg_dump/pg_dump.c
src/bin/pg_dump/pg_dump.h
src/bin/pg_dump/pg_dump_sort.c
src/bin/pg_dump/pg_dumpall.c
src/bin/pg_dump/pg_restore.c
src/bin/pg_dump/t/001_basic.pl
src/bin/pg_dump/t/002_pg_dump.pl
src/bin/pg_resetwal/Makefile
src/bin/pg_resetwal/nls.mk
src/bin/pg_resetwal/pg_resetwal.c
src/bin/pg_resetwal/t/002_corrupted.pl
src/bin/pg_rewind/Makefile
src/bin/pg_rewind/copy_fetch.c
src/bin/pg_rewind/datapagemap.c
src/bin/pg_rewind/file_ops.c
src/bin/pg_rewind/filemap.c
src/bin/pg_rewind/libpq_fetch.c
src/bin/pg_rewind/logging.c
src/bin/pg_rewind/logging.h
src/bin/pg_rewind/nls.mk
src/bin/pg_rewind/parsexlog.c
src/bin/pg_rewind/pg_rewind.c
src/bin/pg_rewind/pg_rewind.h
src/bin/pg_rewind/timeline.c
src/bin/pg_test_fsync/Makefile
src/bin/pg_test_fsync/pg_test_fsync.c
src/bin/pg_upgrade/pg_upgrade.c
src/bin/pg_waldump/Makefile
src/bin/pg_waldump/nls.mk
src/bin/pg_waldump/pg_waldump.c
src/bin/pgbench/pgbench.c
src/bin/psql/command.c
src/bin/psql/common.c
src/bin/psql/common.h
src/bin/psql/copy.c
src/bin/psql/crosstabview.c
src/bin/psql/describe.c
src/bin/psql/help.c
src/bin/psql/input.c
src/bin/psql/large_obj.c
src/bin/psql/mainloop.c
src/bin/psql/nls.mk
src/bin/psql/psqlscanslash.l
src/bin/psql/startup.c
src/bin/psql/tab-complete.c
src/bin/psql/variables.c
src/bin/psql/variables.h
src/bin/scripts/clusterdb.c
src/bin/scripts/common.c
src/bin/scripts/createdb.c
src/bin/scripts/createuser.c
src/bin/scripts/dropdb.c
src/bin/scripts/dropuser.c
src/bin/scripts/nls.mk
src/bin/scripts/pg_isready.c
src/bin/scripts/reindexdb.c
src/bin/scripts/vacuumdb.c
src/common/controldata_utils.c
src/common/file_utils.c
src/common/pgfnames.c
src/common/restricted_token.c
src/common/rmtree.c
src/fe_utils/Makefile
src/fe_utils/logging.c [new file with mode: 0644]
src/fe_utils/psqlscan.l
src/include/common/controldata_utils.h
src/include/common/file_utils.h
src/include/common/restricted_token.h
src/include/fe_utils/logging.h [new file with mode: 0644]
src/include/fe_utils/psqlscan.h
src/interfaces/ecpg/test/Makefile
src/nls-global.mk
src/test/isolation/Makefile
src/test/perl/TestLib.pm
src/test/regress/GNUmakefile
src/test/regress/pg_regress.c
src/tools/msvc/Mkvcbuild.pm

index ed343dd7daec24189a6d5c352b880572accbaca2..b25845ffc6703f24abc6695281daea16d32d95d5 100644 (file)
@@ -274,6 +274,17 @@ PostgreSQL documentation
      </para>
     </listitem>
    </varlistentry>
+
+   <varlistentry>
+    <term><envar>PG_COLOR</envar></term>
+    <listitem>
+     <para>
+      Specifies whether to use color in diagnostics messages.  Possible values
+      are <literal>always</literal>, <literal>auto</literal>,
+      <literal>never</literal>.
+     </para>
+    </listitem>
+   </varlistentry>
   </variablelist>
 
   <para>
index 2658efeb1a1afea6686f78ca523a72878b6a8290..8fc8128bf9c4c50a5b55ef618c837e32b330155e 100644 (file)
@@ -322,6 +322,17 @@ PostgreSQL documentation
      </para>
     </listitem>
    </varlistentry>
+
+   <varlistentry>
+    <term><envar>PG_COLOR</envar></term>
+    <listitem>
+     <para>
+      Specifies whether to use color in diagnostics messages.  Possible values
+      are <literal>always</literal>, <literal>auto</literal>,
+      <literal>never</literal>.
+     </para>
+    </listitem>
+   </varlistentry>
   </variablelist>
 
   <para>
index 22ee99f2cc41c6e1a2a7c8f108a1a839ba5337bc..abe25f17d015b8ebec47fbefbfe16c1ccff3a51a 100644 (file)
@@ -400,6 +400,17 @@ PostgreSQL documentation
      </para>
     </listitem>
    </varlistentry>
+
+   <varlistentry>
+    <term><envar>PG_COLOR</envar></term>
+    <listitem>
+     <para>
+      Specifies whether to use color in diagnostics messages.  Possible values
+      are <literal>always</literal>, <literal>auto</literal>,
+      <literal>never</literal>.
+     </para>
+    </listitem>
+   </varlistentry>
   </variablelist>
 
   <para>
index 38f38f01ce61500e78424bfbf75ca41ab553ee9a..3fbdb337164a16c1daee85c75649b17a405d2c1e 100644 (file)
@@ -228,6 +228,17 @@ PostgreSQL documentation
      </para>
     </listitem>
    </varlistentry>
+
+   <varlistentry>
+    <term><envar>PG_COLOR</envar></term>
+    <listitem>
+     <para>
+      Specifies whether to use color in diagnostics messages.  Possible values
+      are <literal>always</literal>, <literal>auto</literal>,
+      <literal>never</literal>.
+     </para>
+    </listitem>
+   </varlistentry>
   </variablelist>
 
   <para>
index 3d4e4b37b35735c931faed4567d0f0d22d416bb0..72bb7e8535cd8a6e8c27634e957b4a375bea988a 100644 (file)
@@ -220,6 +220,17 @@ PostgreSQL documentation
      </para>
     </listitem>
    </varlistentry>
+
+   <varlistentry>
+    <term><envar>PG_COLOR</envar></term>
+    <listitem>
+     <para>
+      Specifies whether to use color in diagnostics messages.  Possible values
+      are <literal>always</literal>, <literal>auto</literal>,
+      <literal>never</literal>.
+     </para>
+    </listitem>
+   </varlistentry>
   </variablelist>
 
   <para>
index 84fb37c293a3a93fd321b019cd6f31075be38c36..7f323103084b056f0e819e4e9d8d9a4103eca244 100644 (file)
@@ -461,6 +461,17 @@ PostgreSQL documentation
     </listitem>
    </varlistentry>
 
+   <varlistentry>
+    <term><envar>PG_COLOR</envar></term>
+    <listitem>
+     <para>
+      Specifies whether to use color in diagnostics messages.  Possible values
+      are <literal>always</literal>, <literal>auto</literal>,
+      <literal>never</literal>.
+     </para>
+    </listitem>
+   </varlistentry>
+
    <varlistentry>
     <term><envar>TZ</envar></term>
 
index c4f3950e5bc83fe6577bd15572778614391849c5..dd6bce57d2b79668d6dd0ce27861af009ab89869 100644 (file)
@@ -687,6 +687,12 @@ PostgreSQL documentation
    (see <xref linkend="libpq-envars"/>).
   </para>
 
+  <para>
+   The environment variable <envar>PG_COLOR</envar> specifies whether to use
+   color in diagnostics messages.  Possible values are
+   <literal>always</literal>, <literal>auto</literal>,
+   <literal>never</literal>.
+  </para>
  </refsect1>
 
  <refsect1>
index 70339eaec9c23ef1a45ebf405cb8c64dfd696887..d93793da5dd3ac3ee8636d8c3bca23aee81aded0 100644 (file)
@@ -173,6 +173,17 @@ PostgreSQL documentation
      </para>
     </listitem>
    </varlistentry>
+
+   <varlistentry>
+    <term><envar>PG_COLOR</envar></term>
+    <listitem>
+     <para>
+      Specifies whether to use color in diagnostics messages.  Possible values
+      are <literal>always</literal>, <literal>auto</literal>,
+      <literal>never</literal>.
+     </para>
+    </listitem>
+   </varlistentry>
   </variablelist>
  </refsect1>
 
index 32081e9b91cc5674324b2302a73cf11343ebe979..abac59aa500b8e5e997ce0b57241a57263b3d487 100644 (file)
@@ -68,6 +68,17 @@ PostgreSQL documentation
      </para>
     </listitem>
    </varlistentry>
+
+   <varlistentry>
+    <term><envar>PG_COLOR</envar></term>
+    <listitem>
+     <para>
+      Specifies whether to use color in diagnostics messages.  Possible values
+      are <literal>always</literal>, <literal>auto</literal>,
+      <literal>never</literal>.
+     </para>
+    </listitem>
+   </varlistentry>
   </variablelist>
  </refsect1>
 </refentry>
index e0e65f9c21c463c00fd786f9534ea6d31b4dec65..8fa231434742176b92883bd80031aaa829b2ab82 100644 (file)
@@ -1224,6 +1224,17 @@ PostgreSQL documentation
     </listitem>
 
    </varlistentry>
+
+   <varlistentry>
+    <term><envar>PG_COLOR</envar></term>
+    <listitem>
+     <para>
+      Specifies whether to use color in diagnostics messages.  Possible values
+      are <literal>always</literal>, <literal>auto</literal>,
+      <literal>never</literal>.
+     </para>
+    </listitem>
+   </varlistentry>
   </variablelist>
 
   <para>
index e3676cf811f4bad76411c7c94793128f20bf9ecf..24c8c031d64ac1190016bec7a994152827b4a44b 100644 (file)
@@ -695,6 +695,17 @@ PostgreSQL documentation
      </para>
     </listitem>
    </varlistentry>
+
+   <varlistentry>
+    <term><envar>PG_COLOR</envar></term>
+    <listitem>
+     <para>
+      Specifies whether to use color in diagnostics messages.  Possible values
+      are <literal>always</literal>, <literal>auto</literal>,
+      <literal>never</literal>.
+     </para>
+    </listitem>
+   </varlistentry>
   </variablelist>
 
   <para>
index 9567b57ebe2e9de4f2e35f9f8564d95a20a76f85..68447b5093d708e06920bef7edde78edaea45df7 100644 (file)
@@ -164,6 +164,13 @@ PostgreSQL documentation
    also uses the environment variables supported by <application>libpq</application>
    (see <xref linkend="libpq-envars"/>).
   </para>
+
+  <para>
+   The environment variable <envar>PG_COLOR</envar> specifies whether to use
+   color in diagnostics messages.  Possible values are
+   <literal>always</literal>, <literal>auto</literal>,
+   <literal>never</literal>.
+  </para>
  </refsect1>
 
  <refsect1 id="app-pg-isready-notes">
index a18ddd4bff18c544395cb727993f30ab606a04f5..0506120c00bf5449c21bf6748b950bf63166709a 100644 (file)
@@ -408,6 +408,12 @@ PostgreSQL documentation
    (see <xref linkend="libpq-envars"/>).
   </para>
 
+  <para>
+   The environment variable <envar>PG_COLOR</envar> specifies whether to use
+   color in diagnostics messages.  Possible values are
+   <literal>always</literal>, <literal>auto</literal>,
+   <literal>never</literal>.
+  </para>
  </refsect1>
 
  <refsect1>
index 141c5cddce1c9bdf0ec190de85cf7206bf03e258..4c79f90414da226e3897640939e1f3a54658c87d 100644 (file)
@@ -397,6 +397,13 @@ PostgreSQL documentation
    uses the environment variables supported by <application>libpq</application>
    (see <xref linkend="libpq-envars"/>).
   </para>
+
+  <para>
+   The environment variable <envar>PG_COLOR</envar> specifies whether to use
+   color in diagnostics messages.  Possible values are
+   <literal>always</literal>, <literal>auto</literal>,
+   <literal>never</literal>.
+  </para>
  </refsect1>
 
  <refsect1>
index 3f885bdd620c6a2be3f678852806410b6afecb9b..8a9e22d050fb622eec5f09c44a88cced7289e3fa 100644 (file)
@@ -320,6 +320,23 @@ PostgreSQL documentation
   </variablelist>
  </refsect1>
 
+ <refsect1>
+  <title>Environment</title>
+
+  <variablelist>
+   <varlistentry>
+    <term><envar>PG_COLOR</envar></term>
+    <listitem>
+     <para>
+      Specifies whether to use color in diagnostics messages.  Possible values
+      are <literal>always</literal>, <literal>auto</literal>,
+      <literal>never</literal>.
+     </para>
+    </listitem>
+   </varlistentry>
+  </variablelist>
+ </refsect1>
+
  <refsect1>
   <title>Notes</title>
 
index 725acb192c999a6412db397ceddd8d75abb35c6c..cf369a0f3b969e8e787b7b37120e7961f16aa1c7 100644 (file)
      </para>
     </listitem>
    </varlistentry>
+
+   <varlistentry>
+    <term><envar>PG_COLOR</envar></term>
+    <listitem>
+     <para>
+      Specifies whether to use color in diagnostics messages.  Possible values
+      are <literal>always</literal>, <literal>auto</literal>,
+      <literal>never</literal>.
+     </para>
+    </listitem>
+   </varlistentry>
   </variablelist>
 
   <para>
index 53a64ee29ef00d3cb4e2236308a8009a3f2634e1..d98406c420eee6df445cdf784055e627e407701f 100644 (file)
@@ -234,6 +234,13 @@ PostgreSQL documentation
    <application>pg_rewind</application> also uses the environment variables
    supported by <application>libpq</application> (see <xref linkend="libpq-envars"/>).
   </para>
+
+  <para>
+   The environment variable <envar>PG_COLOR</envar> specifies whether to use
+   color in diagnostics messages.  Possible values are
+   <literal>always</literal>, <literal>auto</literal>,
+   <literal>never</literal>.
+  </para>
  </refsect1>
 
  <refsect1>
index 389c314ef3bd87ce2450dc7c294e40106c752e21..329c10e43037ebd88bd6bb959c0d6944a2fe2826 100644 (file)
@@ -206,6 +206,32 @@ PostgreSQL documentation
    </para>
  </refsect1>
 
+ <refsect1>
+  <title>Environment</title>
+
+  <variablelist>
+   <varlistentry>
+    <term><envar>PGDATA</envar></term>
+    <listitem>
+     <para>
+      Data directory; see also the <option>-p</option> option.
+     </para>
+    </listitem>
+   </varlistentry>
+
+   <varlistentry>
+    <term><envar>PG_COLOR</envar></term>
+    <listitem>
+     <para>
+      Specifies whether to use color in diagnostics messages.  Possible values
+      are <literal>always</literal>, <literal>auto</literal>,
+      <literal>never</literal>.
+     </para>
+    </listitem>
+   </varlistentry>
+  </variablelist>
+ </refsect1>
+
  <refsect1>
   <title>Notes</title>
   <para>
index 1b5d82ed8eec1df84ef5d553d104424aff48727f..b29e7547c6a3c26c9e47ec42a09e4ad8edd86659 100644 (file)
@@ -4333,6 +4333,17 @@ $endif
     </listitem>
    </varlistentry>
 
+   <varlistentry>
+    <term><envar>PG_COLOR</envar></term>
+    <listitem>
+     <para>
+      Specifies whether to use color in diagnostics messages.  Possible values
+      are <literal>always</literal>, <literal>auto</literal>,
+      <literal>never</literal>.
+     </para>
+    </listitem>
+   </varlistentry>
+
    <varlistentry>
     <term><envar>PSQL_EDITOR</envar></term>
     <term><envar>EDITOR</envar></term>
index cdfac3fe4f9b2562e8bf88bd1b8287b3d7d2e24c..25b5a72770571b79c192f3d85faa4a42e1adc772 100644 (file)
@@ -352,6 +352,17 @@ PostgreSQL documentation
      </para>
     </listitem>
    </varlistentry>
+
+   <varlistentry>
+    <term><envar>PG_COLOR</envar></term>
+    <listitem>
+     <para>
+      Specifies whether to use color in diagnostics messages.  Possible values
+      are <literal>always</literal>, <literal>auto</literal>,
+      <literal>never</literal>.
+     </para>
+    </listitem>
+   </varlistentry>
   </variablelist>
 
   <para>
index 41c7f3df793e716728d38523b0f1c603b919cda9..47d93456f862009cb3519d13c4d71e7c59c03a02 100644 (file)
@@ -451,6 +451,17 @@ PostgreSQL documentation
      </para>
     </listitem>
    </varlistentry>
+
+   <varlistentry>
+    <term><envar>PG_COLOR</envar></term>
+    <listitem>
+     <para>
+      Specifies whether to use color in diagnostics messages.  Possible values
+      are <literal>always</literal>, <literal>auto</literal>,
+      <literal>never</literal>.
+     </para>
+    </listitem>
+   </varlistentry>
   </variablelist>
 
   <para>
index 9840a55c10a29a130cf88f38cb736f2205c20201..a181e33dd4d27c981cc12d370c8059c8573b4fcf 100644 (file)
@@ -4761,7 +4761,7 @@ ReadControlFile(void)
 void
 UpdateControlFile(void)
 {
-       update_controlfile(DataDir, NULL, ControlFile, true);
+       update_controlfile(DataDir, ControlFile, true);
 }
 
 /*
index e675c33c547a5c1794dd6717b9f18e3706ced051..b42921800b732ac2ca79644e3390cf7053071135 100644 (file)
@@ -54,7 +54,7 @@ pg_control_system(PG_FUNCTION_ARGS)
        tupdesc = BlessTupleDesc(tupdesc);
 
        /* read the control file */
-       ControlFile = get_controlfile(DataDir, NULL, &crc_ok);
+       ControlFile = get_controlfile(DataDir, &crc_ok);
        if (!crc_ok)
                ereport(ERROR,
                                (errmsg("calculated CRC checksum does not match value stored in file")));
@@ -132,7 +132,7 @@ pg_control_checkpoint(PG_FUNCTION_ARGS)
        tupdesc = BlessTupleDesc(tupdesc);
 
        /* Read the control file. */
-       ControlFile = get_controlfile(DataDir, NULL, &crc_ok);
+       ControlFile = get_controlfile(DataDir, &crc_ok);
        if (!crc_ok)
                ereport(ERROR,
                                (errmsg("calculated CRC checksum does not match value stored in file")));
@@ -236,7 +236,7 @@ pg_control_recovery(PG_FUNCTION_ARGS)
        tupdesc = BlessTupleDesc(tupdesc);
 
        /* read the control file */
-       ControlFile = get_controlfile(DataDir, NULL, &crc_ok);
+       ControlFile = get_controlfile(DataDir, &crc_ok);
        if (!crc_ok)
                ereport(ERROR,
                                (errmsg("calculated CRC checksum does not match value stored in file")));
@@ -303,7 +303,7 @@ pg_control_init(PG_FUNCTION_ARGS)
        tupdesc = BlessTupleDesc(tupdesc);
 
        /* read the control file */
-       ControlFile = get_controlfile(DataDir, NULL, &crc_ok);
+       ControlFile = get_controlfile(DataDir, &crc_ok);
        if (!crc_ok)
                ereport(ERROR,
                                (errmsg("calculated CRC checksum does not match value stored in file")));
index 4886090132e08ed35935bda109560e949ee4c5e9..09b59c83246d9f6734b98acf6e232c26ddbb6e78 100644 (file)
@@ -67,6 +67,7 @@
 #include "common/file_utils.h"
 #include "common/restricted_token.h"
 #include "common/username.h"
+#include "fe_utils/logging.h"
 #include "fe_utils/string_utils.h"
 #include "getaddrinfo.h"
 #include "getopt_long.h"
@@ -184,7 +185,7 @@ static const char *default_timezone = NULL;
 "# allows any local user to connect as any PostgreSQL user, including\n" \
 "# the database superuser.  If you do not trust all your local users,\n" \
 "# use another authentication method.\n"
-static char *authwarning = NULL;
+static bool    authwarning = false;
 
 /*
  * Centralized knowledge of switches to pass to backend
@@ -335,7 +336,7 @@ escape_quotes(const char *src)
 
        if (!result)
        {
-               fprintf(stderr, _("%s: out of memory\n"), progname);
+               pg_log_error("out of memory");
                exit(1);
        }
        return result;
@@ -491,8 +492,7 @@ readfile(const char *path)
 
        if ((infile = fopen(path, "r")) == NULL)
        {
-               fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
-                               progname, path, strerror(errno));
+               pg_log_error("could not open file \"%s\" for reading: %m", path);
                exit(1);
        }
 
@@ -547,24 +547,21 @@ writefile(char *path, char **lines)
 
        if ((out_file = fopen(path, "w")) == NULL)
        {
-               fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
-                               progname, path, strerror(errno));
+               pg_log_error("could not open file \"%s\" for writing: %m", path);
                exit(1);
        }
        for (line = lines; *line != NULL; line++)
        {
                if (fputs(*line, out_file) < 0)
                {
-                       fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
-                                       progname, path, strerror(errno));
+                       pg_log_error("could not write file \"%s\": %m", path);
                        exit(1);
                }
                free(*line);
        }
        if (fclose(out_file))
        {
-               fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
-                               progname, path, strerror(errno));
+               pg_log_error("could not write file \"%s\": %m", path);
                exit(1);
        }
 }
@@ -582,8 +579,7 @@ popen_check(const char *command, const char *mode)
        errno = 0;
        cmdfd = popen(command, mode);
        if (cmdfd == NULL)
-               fprintf(stderr, _("%s: could not execute command \"%s\": %s\n"),
-                               progname, command, strerror(errno));
+               pg_log_error("could not execute command \"%s\": %m", command);
        return cmdfd;
 }
 
@@ -601,52 +597,41 @@ cleanup_directories_atexit(void)
        {
                if (made_new_pgdata)
                {
-                       fprintf(stderr, _("%s: removing data directory \"%s\"\n"),
-                                       progname, pg_data);
+                       pg_log_info("removing data directory \"%s\"", pg_data);
                        if (!rmtree(pg_data, true))
-                               fprintf(stderr, _("%s: failed to remove data directory\n"),
-                                               progname);
+                               pg_log_error("failed to remove data directory");
                }
                else if (found_existing_pgdata)
                {
-                       fprintf(stderr,
-                                       _("%s: removing contents of data directory \"%s\"\n"),
-                                       progname, pg_data);
+                       pg_log_info("removing contents of data directory \"%s\"",
+                                               pg_data);
                        if (!rmtree(pg_data, false))
-                               fprintf(stderr, _("%s: failed to remove contents of data directory\n"),
-                                               progname);
+                               pg_log_error("failed to remove contents of data directory");
                }
 
                if (made_new_xlogdir)
                {
-                       fprintf(stderr, _("%s: removing WAL directory \"%s\"\n"),
-                                       progname, xlog_dir);
+                       pg_log_info("removing WAL directory \"%s\"", xlog_dir);
                        if (!rmtree(xlog_dir, true))
-                               fprintf(stderr, _("%s: failed to remove WAL directory\n"),
-                                               progname);
+                               pg_log_error("failed to remove WAL directory");
                }
                else if (found_existing_xlogdir)
                {
-                       fprintf(stderr,
-                                       _("%s: removing contents of WAL directory \"%s\"\n"),
-                                       progname, xlog_dir);
+                       pg_log_info("removing contents of WAL directory \"%s\"", xlog_dir);
                        if (!rmtree(xlog_dir, false))
-                               fprintf(stderr, _("%s: failed to remove contents of WAL directory\n"),
-                                               progname);
+                               pg_log_error("failed to remove contents of WAL directory");
                }
                /* otherwise died during startup, do nothing! */
        }
        else
        {
                if (made_new_pgdata || found_existing_pgdata)
-                       fprintf(stderr,
-                                       _("%s: data directory \"%s\" not removed at user's request\n"),
-                                       progname, pg_data);
+                       pg_log_info("data directory \"%s\" not removed at user's request",
+                                               pg_data);
 
                if (made_new_xlogdir || found_existing_xlogdir)
-                       fprintf(stderr,
-                                       _("%s: WAL directory \"%s\" not removed at user's request\n"),
-                                       progname, xlog_dir);
+                       pg_log_info("WAL directory \"%s\" not removed at user's request",
+                                               xlog_dir);
        }
 }
 
@@ -663,12 +648,10 @@ get_id(void)
 #ifndef WIN32
        if (geteuid() == 0)                     /* 0 is root's uid */
        {
+               pg_log_error("cannot be run as root");
                fprintf(stderr,
-                               _("%s: cannot be run as root\n"
-                                 "Please log in (using, e.g., \"su\") as the "
-                                 "(unprivileged) user that will\n"
-                                 "own the server process.\n"),
-                               progname);
+                               _("Please log in (using, e.g., \"su\") as the (unprivileged) user that will\n"
+                                 "own the server process.\n"));
                exit(1);
        }
 #endif
@@ -700,8 +683,8 @@ get_encoding_id(const char *encoding_name)
                if ((enc = pg_valid_server_encoding(encoding_name)) >= 0)
                        return enc;
        }
-       fprintf(stderr, _("%s: \"%s\" is not a valid server encoding name\n"),
-                       progname, encoding_name ? encoding_name : "(null)");
+       pg_log_error("\"%s\" is not a valid server encoding name",
+                                encoding_name ? encoding_name : "(null)");
        exit(1);
 }
 
@@ -831,17 +814,14 @@ check_input(char *path)
        {
                if (errno == ENOENT)
                {
-                       fprintf(stderr,
-                                       _("%s: file \"%s\" does not exist\n"), progname, path);
+                       pg_log_error("file \"%s\" does not exist", path);
                        fprintf(stderr,
                                        _("This might mean you have a corrupted installation or identified\n"
                                          "the wrong directory with the invocation option -L.\n"));
                }
                else
                {
-                       fprintf(stderr,
-                                       _("%s: could not access file \"%s\": %s\n"), progname, path,
-                                       strerror(errno));
+                       pg_log_error("could not access file \"%s\": %m", path);
                        fprintf(stderr,
                                        _("This might mean you have a corrupted installation or identified\n"
                                          "the wrong directory with the invocation option -L.\n"));
@@ -850,8 +830,7 @@ check_input(char *path)
        }
        if (!S_ISREG(statbuf.st_mode))
        {
-               fprintf(stderr,
-                               _("%s: file \"%s\" is not a regular file\n"), progname, path);
+               pg_log_error("file \"%s\" is not a regular file", path);
                fprintf(stderr,
                                _("This might mean you have a corrupted installation or identified\n"
                                  "the wrong directory with the invocation option -L.\n"));
@@ -876,15 +855,13 @@ write_version_file(const char *extrapath)
 
        if ((version_file = fopen(path, PG_BINARY_W)) == NULL)
        {
-               fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
-                               progname, path, strerror(errno));
+               pg_log_error("could not open file \"%s\" for writing: %m", path);
                exit(1);
        }
        if (fprintf(version_file, "%s\n", PG_MAJORVERSION) < 0 ||
                fclose(version_file))
        {
-               fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
-                               progname, path, strerror(errno));
+               pg_log_error("could not write file \"%s\": %m", path);
                exit(1);
        }
        free(path);
@@ -904,14 +881,12 @@ set_null_conf(void)
        conf_file = fopen(path, PG_BINARY_W);
        if (conf_file == NULL)
        {
-               fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
-                               progname, path, strerror(errno));
+               pg_log_error("could not open file \"%s\" for writing: %m", path);
                exit(1);
        }
        if (fclose(conf_file))
        {
-               fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
-                               progname, path, strerror(errno));
+               pg_log_error("could not write file \"%s\": %m", path);
                exit(1);
        }
        free(path);
@@ -1261,8 +1236,7 @@ setup_config(void)
        writefile(path, conflines);
        if (chmod(path, pg_file_create_mode) != 0)
        {
-               fprintf(stderr, _("%s: could not change permissions of \"%s\": %s\n"),
-                               progname, path, strerror(errno));
+               pg_log_error("could not change permissions of \"%s\": %m", path);
                exit(1);
        }
 
@@ -1281,8 +1255,7 @@ setup_config(void)
        writefile(path, autoconflines);
        if (chmod(path, pg_file_create_mode) != 0)
        {
-               fprintf(stderr, _("%s: could not change permissions of \"%s\": %s\n"),
-                               progname, path, strerror(errno));
+               pg_log_error("could not change permissions of \"%s\": %m", path);
                exit(1);
        }
 
@@ -1368,8 +1341,7 @@ setup_config(void)
        writefile(path, conflines);
        if (chmod(path, pg_file_create_mode) != 0)
        {
-               fprintf(stderr, _("%s: could not change permissions of \"%s\": %s\n"),
-                               progname, path, strerror(errno));
+               pg_log_error("could not change permissions of \"%s\": %m", path);
                exit(1);
        }
 
@@ -1384,8 +1356,7 @@ setup_config(void)
        writefile(path, conflines);
        if (chmod(path, pg_file_create_mode) != 0)
        {
-               fprintf(stderr, _("%s: could not change permissions of \"%s\": %s\n"),
-                               progname, path, strerror(errno));
+               pg_log_error("could not change permissions of \"%s\": %m", path);
                exit(1);
        }
 
@@ -1419,11 +1390,11 @@ bootstrap_template1(void)
 
        if (strcmp(headerline, *bki_lines) != 0)
        {
+               pg_log_error("input file \"%s\" does not belong to PostgreSQL %s",
+                                        bki_file, PG_VERSION);
                fprintf(stderr,
-                               _("%s: input file \"%s\" does not belong to PostgreSQL %s\n"
-                                 "Check your installation or specify the correct path "
-                                 "using the option -L.\n"),
-                               progname, bki_file, PG_VERSION);
+                               _("Check your installation or specify the correct path "
+                                 "using the option -L.\n"));
                exit(1);
        }
 
@@ -1560,18 +1531,18 @@ get_su_pwd(void)
 
                if (!pwf)
                {
-                       fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
-                                       progname, pwfilename, strerror(errno));
+                       pg_log_error("could not open file \"%s\" for reading: %m",
+                                                pwfilename);
                        exit(1);
                }
                if (!fgets(pwd1, sizeof(pwd1), pwf))
                {
                        if (ferror(pwf))
-                               fprintf(stderr, _("%s: could not read password from file \"%s\": %s\n"),
-                                               progname, pwfilename, strerror(errno));
+                               pg_log_error("could not read password from file \"%s\": %m",
+                                                        pwfilename);
                        else
-                               fprintf(stderr, _("%s: password file \"%s\" is empty\n"),
-                                               progname, pwfilename);
+                               pg_log_error("password file \"%s\" is empty",
+                                                        pwfilename);
                        exit(1);
                }
                fclose(pwf);
@@ -2237,8 +2208,7 @@ check_locale_name(int category, const char *locale, char **canonname)
        save = setlocale(category, NULL);
        if (!save)
        {
-               fprintf(stderr, _("%s: setlocale() failed\n"),
-                               progname);
+               pg_log_error("setlocale() failed");
                exit(1);
        }
 
@@ -2259,8 +2229,7 @@ check_locale_name(int category, const char *locale, char **canonname)
        /* restore old value. */
        if (!setlocale(category, save))
        {
-               fprintf(stderr, _("%s: failed to restore old locale \"%s\"\n"),
-                               progname, save);
+               pg_log_error("failed to restore old locale \"%s\"", save);
                exit(1);
        }
        free(save);
@@ -2269,8 +2238,7 @@ check_locale_name(int category, const char *locale, char **canonname)
        if (res == NULL)
        {
                if (*locale)
-                       fprintf(stderr, _("%s: invalid locale name \"%s\"\n"),
-                                       progname, locale);
+                       pg_log_error("invalid locale name \"%s\"", locale);
                else
                {
                        /*
@@ -2281,8 +2249,7 @@ check_locale_name(int category, const char *locale, char **canonname)
                         * setlocale's behavior is implementation-specific, it's hard to
                         * be sure what it didn't like.  Print a safe generic message.
                         */
-                       fprintf(stderr, _("%s: invalid locale settings; check LANG and LC_* environment variables\n"),
-                                       progname);
+                       pg_log_error("invalid locale settings; check LANG and LC_* environment variables");
                }
                exit(1);
        }
@@ -2309,7 +2276,7 @@ check_locale_encoding(const char *locale, int user_enc)
 #endif
                  user_enc == PG_SQL_ASCII))
        {
-               fprintf(stderr, _("%s: encoding mismatch\n"), progname);
+               pg_log_error("encoding mismatch");
                fprintf(stderr,
                                _("The encoding you selected (%s) and the encoding that the\n"
                                  "selected locale uses (%s) do not match.  This would lead to\n"
@@ -2427,9 +2394,7 @@ check_authmethod_unspecified(const char **authmethod)
 {
        if (*authmethod == NULL)
        {
-               authwarning = _("\nWARNING: enabling \"trust\" authentication for local connections\n"
-                                               "You can change this by editing pg_hba.conf or using the option -A, or\n"
-                                               "--auth-local and --auth-host, the next time you run initdb.\n");
+               authwarning = true;
                *authmethod = "trust";
        }
 }
@@ -2449,8 +2414,8 @@ check_authmethod_valid(const char *authmethod, const char *const *valid_methods,
                                return;
        }
 
-       fprintf(stderr, _("%s: invalid authentication method \"%s\" for \"%s\" connections\n"),
-                       progname, authmethod, conntype);
+       pg_log_error("invalid authentication method \"%s\" for \"%s\" connections",
+                                authmethod, conntype);
        exit(1);
 }
 
@@ -2465,7 +2430,7 @@ check_need_password(const char *authmethodlocal, const char *authmethodhost)
                 strcmp(authmethodhost, "scram-sha-256") == 0) &&
                !(pwprompt || pwfilename))
        {
-               fprintf(stderr, _("%s: must specify a password for the superuser to enable %s authentication\n"), progname,
+               pg_log_error("must specify a password for the superuser to enable %s authentication",
                                (strcmp(authmethodlocal, "md5") == 0 ||
                                 strcmp(authmethodlocal, "password") == 0 ||
                                 strcmp(authmethodlocal, "scram-sha-256") == 0)
@@ -2492,12 +2457,11 @@ setup_pgdata(void)
                }
                else
                {
+                       pg_log_error("no data directory specified");
                        fprintf(stderr,
-                                       _("%s: no data directory specified\n"
-                                         "You must identify the directory where the data for this database system\n"
+                                       _("You must identify the directory where the data for this database system\n"
                                          "will reside.  Do this with either the invocation option -D or the\n"
-                                         "environment variable PGDATA.\n"),
-                                       progname);
+                                         "environment variable PGDATA.\n"));
                        exit(1);
                }
        }
@@ -2530,18 +2494,15 @@ setup_bin_paths(const char *argv0)
                        strlcpy(full_path, progname, sizeof(full_path));
 
                if (ret == -1)
-                       fprintf(stderr,
-                                       _("The program \"postgres\" is needed by %s "
-                                         "but was not found in the\n"
-                                         "same directory as \"%s\".\n"
-                                         "Check your installation.\n"),
-                                       progname, full_path);
+                       pg_log_error("The program \"postgres\" is needed by %s but was not found in the\n"
+                                                "same directory as \"%s\".\n"
+                                                "Check your installation.",
+                                                full_path, progname);
                else
-                       fprintf(stderr,
-                                       _("The program \"postgres\" was found by \"%s\"\n"
-                                         "but was not the same version as %s.\n"
-                                         "Check your installation.\n"),
-                                       full_path, progname);
+                       pg_log_error("The program \"postgres\" was found by \"%s\"\n"
+                                                "but was not the same version as %s.\n"
+                                                "Check your installation.",
+                                                full_path, progname);
                exit(1);
        }
 
@@ -2557,7 +2518,7 @@ setup_bin_paths(const char *argv0)
        }
        else if (!is_absolute_path(share_path))
        {
-               fprintf(stderr, _("%s: input file location must be an absolute path\n"), progname);
+               pg_log_error("input file location must be an absolute path");
                exit(1);
        }
 
@@ -2601,8 +2562,8 @@ setup_locale_encoding(void)
                if (ctype_enc == -1)
                {
                        /* Couldn't recognize the locale's codeset */
-                       fprintf(stderr, _("%s: could not find suitable encoding for locale \"%s\"\n"),
-                                       progname, lc_ctype);
+                       pg_log_error("could not find suitable encoding for locale \"%s\"",
+                                                lc_ctype);
                        fprintf(stderr, _("Rerun %s with the -E option.\n"), progname);
                        fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                        progname);
@@ -2622,9 +2583,8 @@ setup_locale_encoding(void)
                                   pg_encoding_to_char(ctype_enc),
                                   pg_encoding_to_char(encodingid));
 #else
-                       fprintf(stderr,
-                                       _("%s: locale \"%s\" requires unsupported encoding \"%s\"\n"),
-                                       progname, lc_ctype, pg_encoding_to_char(ctype_enc));
+                       pg_log_error("locale \"%s\" requires unsupported encoding \"%s\"",
+                                                lc_ctype, pg_encoding_to_char(ctype_enc));
                        fprintf(stderr,
                                        _("Encoding \"%s\" is not allowed as a server-side encoding.\n"
                                          "Rerun %s with a different locale selection.\n"),
@@ -2774,8 +2734,7 @@ create_data_directory(void)
 
                        if (pg_mkdir_p(pg_data, pg_dir_create_mode) != 0)
                        {
-                               fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
-                                               progname, pg_data, strerror(errno));
+                               pg_log_error("could not create directory \"%s\": %m", pg_data);
                                exit(1);
                        }
                        else
@@ -2792,8 +2751,8 @@ create_data_directory(void)
 
                        if (chmod(pg_data, pg_dir_create_mode) != 0)
                        {
-                               fprintf(stderr, _("%s: could not change permissions of directory \"%s\": %s\n"),
-                                               progname, pg_data, strerror(errno));
+                               pg_log_error("could not change permissions of directory \"%s\": %m",
+                                                        pg_data);
                                exit(1);
                        }
                        else
@@ -2806,9 +2765,7 @@ create_data_directory(void)
                case 3:
                case 4:
                        /* Present and not empty */
-                       fprintf(stderr,
-                                       _("%s: directory \"%s\" exists but is not empty\n"),
-                                       progname, pg_data);
+                       pg_log_error("directory \"%s\" exists but is not empty", pg_data);
                        if (ret != 4)
                                warn_on_mount_point(ret);
                        else
@@ -2821,8 +2778,7 @@ create_data_directory(void)
 
                default:
                        /* Trouble accessing directory */
-                       fprintf(stderr, _("%s: could not access directory \"%s\": %s\n"),
-                                       progname, pg_data, strerror(errno));
+                       pg_log_error("could not access directory \"%s\": %m", pg_data);
                        exit(1);
        }
 }
@@ -2845,7 +2801,7 @@ create_xlog_or_symlink(void)
                canonicalize_path(xlog_dir);
                if (!is_absolute_path(xlog_dir))
                {
-                       fprintf(stderr, _("%s: WAL directory location must be an absolute path\n"), progname);
+                       pg_log_error("WAL directory location must be an absolute path");
                        exit(1);
                }
 
@@ -2860,8 +2816,8 @@ create_xlog_or_symlink(void)
 
                                if (pg_mkdir_p(xlog_dir, pg_dir_create_mode) != 0)
                                {
-                                       fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
-                                                       progname, xlog_dir, strerror(errno));
+                                       pg_log_error("could not create directory \"%s\": %m",
+                                                                xlog_dir);
                                        exit(1);
                                }
                                else
@@ -2878,8 +2834,8 @@ create_xlog_or_symlink(void)
 
                                if (chmod(xlog_dir, pg_dir_create_mode) != 0)
                                {
-                                       fprintf(stderr, _("%s: could not change permissions of directory \"%s\": %s\n"),
-                                                       progname, xlog_dir, strerror(errno));
+                                       pg_log_error("could not change permissions of directory \"%s\": %m",
+                                                                xlog_dir);
                                        exit(1);
                                }
                                else
@@ -2892,9 +2848,7 @@ create_xlog_or_symlink(void)
                        case 3:
                        case 4:
                                /* Present and not empty */
-                               fprintf(stderr,
-                                               _("%s: directory \"%s\" exists but is not empty\n"),
-                                               progname, xlog_dir);
+                               pg_log_error("directory \"%s\" exists but is not empty", xlog_dir);
                                if (ret != 4)
                                        warn_on_mount_point(ret);
                                else
@@ -2906,20 +2860,19 @@ create_xlog_or_symlink(void)
 
                        default:
                                /* Trouble accessing directory */
-                               fprintf(stderr, _("%s: could not access directory \"%s\": %s\n"),
-                                               progname, xlog_dir, strerror(errno));
+                               pg_log_error("could not access directory \"%s\": %m", xlog_dir);
                                exit(1);
                }
 
 #ifdef HAVE_SYMLINK
                if (symlink(xlog_dir, subdirloc) != 0)
                {
-                       fprintf(stderr, _("%s: could not create symbolic link \"%s\": %s\n"),
-                                       progname, subdirloc, strerror(errno));
+                       pg_log_error("could not create symbolic link \"%s\": %m",
+                                                subdirloc);
                        exit(1);
                }
 #else
-               fprintf(stderr, _("%s: symlinks are not supported on this platform\n"), progname);
+               pg_log_error("symlinks are not supported on this platform");
                exit(1);
 #endif
        }
@@ -2928,8 +2881,8 @@ create_xlog_or_symlink(void)
                /* Without -X option, just make the subdirectory normally */
                if (mkdir(subdirloc, pg_dir_create_mode) < 0)
                {
-                       fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
-                                       progname, subdirloc, strerror(errno));
+                       pg_log_error("could not create directory \"%s\": %m",
+                                                subdirloc);
                        exit(1);
                }
        }
@@ -2990,8 +2943,7 @@ initialize_data_directory(void)
                 */
                if (mkdir(path, pg_dir_create_mode) < 0)
                {
-                       fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
-                                       progname, path, strerror(errno));
+                       pg_log_error("could not create directory \"%s\": %m", path);
                        exit(1);
                }
 
@@ -3115,14 +3067,14 @@ main(int argc, char *argv[])
        char            pg_ctl_path[MAXPGPATH];
 
        /*
-        * Ensure that buffering behavior of stdout and stderr matches what it is
+        * Ensure that buffering behavior of stdout matches what it is
         * in interactive usage (at least on most platforms).  This prevents
         * unexpected output ordering when, eg, output is redirected to a file.
         * POSIX says we must do this before any other usage of these files.
         */
        setvbuf(stdout, NULL, PG_IOLBF, 0);
-       setvbuf(stderr, NULL, _IONBF, 0);
 
+       pg_logging_init(argv[0]);
        progname = get_progname(argv[0]);
        set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("initdb"));
 
@@ -3260,8 +3212,8 @@ main(int argc, char *argv[])
 
        if (optind < argc)
        {
-               fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
-                               progname, argv[optind]);
+               pg_log_error("too many command-line arguments (first is \"%s\")",
+                                        argv[optind]);
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                progname);
                exit(1);
@@ -3277,21 +3229,20 @@ main(int argc, char *argv[])
                /* must check that directory is readable */
                if (pg_check_dir(pg_data) <= 0)
                {
-                       fprintf(stderr, _("%s: could not access directory \"%s\": %s\n"),
-                                       progname, pg_data, strerror(errno));
+                       pg_log_error("could not access directory \"%s\": %m", pg_data);
                        exit(1);
                }
 
                fputs(_("syncing data to disk ... "), stdout);
                fflush(stdout);
-               fsync_pgdata(pg_data, progname, PG_VERSION_NUM);
+               fsync_pgdata(pg_data, PG_VERSION_NUM);
                check_ok();
                return 0;
        }
 
        if (pwprompt && pwfilename)
        {
-               fprintf(stderr, _("%s: password prompt and password file cannot be specified together\n"), progname);
+               pg_log_error("password prompt and password file cannot be specified together");
                exit(1);
        }
 
@@ -3316,21 +3267,17 @@ main(int argc, char *argv[])
                /* verify that wal segment size is valid */
                if (endptr == str_wal_segment_size_mb || *endptr != '\0')
                {
-                       fprintf(stderr,
-                                       _("%s: argument of --wal-segsize must be a number\n"),
-                                       progname);
+                       pg_log_error("argument of --wal-segsize must be a number");
                        exit(1);
                }
                if (!IsValidWalSegSize(wal_segment_size_mb * 1024 * 1024))
                {
-                       fprintf(stderr,
-                                       _("%s: argument of --wal-segsize must be a power of 2 between 1 and 1024\n"),
-                                       progname);
+                       pg_log_error("argument of --wal-segsize must be a power of 2 between 1 and 1024");
                        exit(1);
                }
        }
 
-       get_restricted_token(progname);
+       get_restricted_token();
 
        setup_pgdata();
 
@@ -3342,7 +3289,7 @@ main(int argc, char *argv[])
 
        if (strncmp(username, "pg_", 3) == 0)
        {
-               fprintf(stderr, _("%s: superuser name \"%s\" is disallowed; role names cannot begin with \"pg_\"\n"), progname, username);
+               pg_log_error("superuser name \"%s\" is disallowed; role names cannot begin with \"pg_\"", username);
                exit(1);
        }
 
@@ -3377,14 +3324,19 @@ main(int argc, char *argv[])
        {
                fputs(_("syncing data to disk ... "), stdout);
                fflush(stdout);
-               fsync_pgdata(pg_data, progname, PG_VERSION_NUM);
+               fsync_pgdata(pg_data, PG_VERSION_NUM);
                check_ok();
        }
        else
                printf(_("\nSync to disk skipped.\nThe data directory might become corrupt if the operating system crashes.\n"));
 
-       if (authwarning != NULL)
-               fprintf(stderr, "%s", authwarning);
+       if (authwarning)
+       {
+               printf("\n");
+               pg_log_warning("enabling \"trust\" authentication for local connections");
+               fprintf(stderr, _("You can change this by editing pg_hba.conf or using the option -A, or\n"
+                                                 "--auth-local and --auth-host, the next time you run initdb.\n"));
+       }
 
        /*
         * Build up a shell command to tell the user how to start the server
index b0ce62980a00dd9fb7dcdc689514713f96c2e9d1..803388d4c7b92e1306fbacc882fc48daaca7a5d0 100644 (file)
@@ -1,5 +1,6 @@
 # src/bin/initdb/nls.mk
 CATALOG_NAME     = initdb
 AVAIL_LANGUAGES  = cs de es fr he it ja ko pl pt_BR ru sv tr vi zh_CN
-GETTEXT_FILES    = findtimezone.c initdb.c ../../common/exec.c ../../common/fe_memutils.c ../../common/file_utils.c ../../common/pgfnames.c ../../common/restricted_token.c ../../common/rmtree.c ../../common/username.c ../../common/wait_error.c ../../port/dirmod.c
-GETTEXT_TRIGGERS = simple_prompt
+GETTEXT_FILES    = $(FRONTEND_COMMON_GETTEXT_FILES) findtimezone.c initdb.c ../../common/exec.c ../../common/fe_memutils.c ../../common/file_utils.c ../../common/pgfnames.c ../../common/restricted_token.c ../../common/rmtree.c ../../common/username.c ../../common/wait_error.c ../../port/dirmod.c
+GETTEXT_TRIGGERS = $(FRONTEND_COMMON_GETTEXT_TRIGGERS) simple_prompt
+GETTEXT_FLAGS    = $(FRONTEND_COMMON_GETTEXT_FLAGS)
index c5bf99db0f43159b232c2dfa6f155a90e170f8a5..14e834677b2bdaf3e3f10fffcfd74335f3d57925 100644 (file)
@@ -7,11 +7,13 @@ subdir = src/bin/pg_archivecleanup
 top_builddir = ../../..
 include $(top_builddir)/src/Makefile.global
 
+LDFLAGS_INTERNAL += -L$(top_builddir)/src/fe_utils -lpgfeutils
+
 OBJS   = pg_archivecleanup.o $(WIN32RES)
 
 all: pg_archivecleanup
 
-pg_archivecleanup: $(OBJS) | submake-libpgport
+pg_archivecleanup: $(OBJS) | submake-libpgport submake-libpgfeutils
        $(CC) $(CFLAGS) $^ $(LDFLAGS) $(LDFLAGS_EX) $(LIBS) -o $@$(X)
 
 install: all installdirs
index 2cd81d32a7d0443f7988f6154a30d43a1306def0..c2d625c52ff296f2ec5b4e935233b867b3e8571f 100644 (file)
@@ -1,4 +1,6 @@
 # src/bin/pg_archivecleanup/nls.mk
 CATALOG_NAME     = pg_archivecleanup
 AVAIL_LANGUAGES  =de es fr ja ko pl ru sv tr vi
-GETTEXT_FILES    = pg_archivecleanup.c
+GETTEXT_FILES    = $(FRONTEND_COMMON_GETTEXT_FILES) pg_archivecleanup.c
+GETTEXT_TRIGGERS = $(FRONTEND_COMMON_GETTEXT_TRIGGERS)
+GETTEXT_FLAGS    = $(FRONTEND_COMMON_GETTEXT_FLAGS)
index 4c3a2de04539bdc3c90e045ff418445d3f290d2d..b297f210df616ea97eaa8194d4ee0eb66beb3a8c 100644 (file)
 
 #include "pg_getopt.h"
 
+#include "fe_utils/logging.h"
+
 #include "access/xlog_internal.h"
 
 const char *progname;
 
 /* Options and defaults */
-bool           debug = false;          /* are we debugging? */
 bool           dryrun = false;         /* are we performing a dry-run operation? */
 char      *additional_ext = NULL;      /* Extension to remove from filenames */
 
 char      *archiveLocation;    /* where to find the archive? */
 char      *restartWALFileName; /* the file from which we can restart restore */
-char           WALFilePath[MAXPGPATH * 2]; /* the file path including archive */
 char           exclusiveCleanupFileName[MAXFNAMELEN];  /* the oldest file we want
                                                                                                         * to remain in archive */
 
@@ -65,8 +65,8 @@ Initialize(void)
        if (stat(archiveLocation, &stat_buf) != 0 ||
                !S_ISDIR(stat_buf.st_mode))
        {
-               fprintf(stderr, _("%s: archive location \"%s\" does not exist\n"),
-                               progname, archiveLocation);
+               pg_log_error("archive location \"%s\" does not exist",
+                                        archiveLocation);
                exit(2);
        }
 }
@@ -123,6 +123,8 @@ CleanupPriorWALFiles(void)
                        if ((IsXLogFileName(walfile) || IsPartialXLogFileName(walfile)) &&
                                strcmp(walfile + 8, exclusiveCleanupFileName + 8) < 0)
                        {
+                               char            WALFilePath[MAXPGPATH * 2]; /* the file path including archive */
+
                                /*
                                 * Use the original file name again now, including any
                                 * extension that might have been chopped off before testing
@@ -139,37 +141,32 @@ CleanupPriorWALFiles(void)
                                         * user can pipe the output into some other program.
                                         */
                                        printf("%s\n", WALFilePath);
-                                       if (debug)
-                                               fprintf(stderr,
-                                                               _("%s: file \"%s\" would be removed\n"),
-                                                               progname, WALFilePath);
+                                       pg_log_debug("file \"%s\" would be removed", WALFilePath);
                                        continue;
                                }
 
-                               if (debug)
-                                       fprintf(stderr, _("%s: removing file \"%s\"\n"),
-                                                       progname, WALFilePath);
+                               pg_log_debug("removing file \"%s\"", WALFilePath);
 
                                rc = unlink(WALFilePath);
                                if (rc != 0)
                                {
-                                       fprintf(stderr, _("%s: ERROR: could not remove file \"%s\": %s\n"),
-                                                       progname, WALFilePath, strerror(errno));
+                                       pg_log_error("could not remove file \"%s\": %m",
+                                                                WALFilePath);
                                        break;
                                }
                        }
                }
 
                if (errno)
-                       fprintf(stderr, _("%s: could not read archive location \"%s\": %s\n"),
-                                       progname, archiveLocation, strerror(errno));
+                       pg_log_error("could not read archive location \"%s\": %m",
+                                                archiveLocation);
                if (closedir(xldir))
-                       fprintf(stderr, _("%s: could not close archive location \"%s\": %s\n"),
-                                       progname, archiveLocation, strerror(errno));
+                       pg_log_error("could not close archive location \"%s\": %m",
+                                                archiveLocation);
        }
        else
-               fprintf(stderr, _("%s: could not open archive location \"%s\": %s\n"),
-                               progname, archiveLocation, strerror(errno));
+               pg_log_error("could not open archive location \"%s\": %m",
+                                        archiveLocation);
 }
 
 /*
@@ -241,7 +238,7 @@ SetWALFileNameForCleanup(void)
 
        if (!fnameOK)
        {
-               fprintf(stderr, _("%s: invalid file name argument\n"), progname);
+               pg_log_error("invalid file name argument");
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
                exit(2);
        }
@@ -282,6 +279,7 @@ main(int argc, char **argv)
 {
        int                     c;
 
+       pg_logging_init(argv[0]);
        set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_archivecleanup"));
        progname = get_progname(argv[0]);
 
@@ -304,7 +302,7 @@ main(int argc, char **argv)
                switch (c)
                {
                        case 'd':                       /* Debug mode */
-                               debug = true;
+                               pg_logging_set_level(PG_LOG_DEBUG);
                                break;
                        case 'n':                       /* Dry-Run mode */
                                dryrun = true;
@@ -334,7 +332,7 @@ main(int argc, char **argv)
        }
        else
        {
-               fprintf(stderr, _("%s: must specify archive location\n"), progname);
+               pg_log_error("must specify archive location");
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
                exit(2);
        }
@@ -346,14 +344,14 @@ main(int argc, char **argv)
        }
        else
        {
-               fprintf(stderr, _("%s: must specify oldest kept WAL file\n"), progname);
+               pg_log_error("must specify oldest kept WAL file");
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
                exit(2);
        }
 
        if (optind < argc)
        {
-               fprintf(stderr, _("%s: too many command-line arguments\n"), progname);
+               pg_log_error("too many command-line arguments");
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
                exit(2);
        }
@@ -368,13 +366,8 @@ main(int argc, char **argv)
         */
        SetWALFileNameForCleanup();
 
-       if (debug)
-       {
-               snprintf(WALFilePath, MAXPGPATH, "%s/%s",
+       pg_log_debug("keeping WAL file \"%s/%s\" and later",
                                 archiveLocation, exclusiveCleanupFileName);
-               fprintf(stderr, _("%s: keeping WAL file \"%s\" and later\n"),
-                               progname, WALFilePath);
-       }
 
        /*
         * Remove WAL files older than cut-off
index f7694343fc7236662f91fc521b993119e1043fc7..fece5551bda7f589638a9aaef6368889111ffc88 100644 (file)
@@ -1,5 +1,6 @@
 # src/bin/pg_basebackup/nls.mk
 CATALOG_NAME     = pg_basebackup
 AVAIL_LANGUAGES  = de es fr he it ja ko pl pt_BR ru sv tr vi zh_CN
-GETTEXT_FILES    = pg_basebackup.c pg_receivewal.c pg_recvlogical.c receivelog.c streamutil.c walmethods.c ../../common/fe_memutils.c ../../common/file_utils.c
-GETTEXT_TRIGGERS = simple_prompt tar_set_error
+GETTEXT_FILES    = $(FRONTEND_COMMON_GETTEXT_FILES) pg_basebackup.c pg_receivewal.c pg_recvlogical.c receivelog.c streamutil.c walmethods.c ../../common/fe_memutils.c ../../common/file_utils.c
+GETTEXT_TRIGGERS = $(FRONTEND_COMMON_GETTEXT_TRIGGERS) simple_prompt tar_set_error
+GETTEXT_FLAGS    = $(FRONTEND_COMMON_GETTEXT_FLAGS)
index 916371232bfaafaf3d89f1088c67b9664ffaa278..1a735b80467c43760591cc697f4f95a19603b4c1 100644 (file)
@@ -30,6 +30,7 @@
 #include "common/file_perm.h"
 #include "common/file_utils.h"
 #include "common/string.h"
+#include "fe_utils/logging.h"
 #include "fe_utils/string_utils.h"
 #include "getopt_long.h"
 #include "libpq-fe.h"
@@ -167,57 +168,41 @@ cleanup_directories_atexit(void)
        {
                if (made_new_pgdata)
                {
-                       fprintf(stderr, _("%s: removing data directory \"%s\"\n"),
-                                       progname, basedir);
+                       pg_log_info("removing data directory \"%s\"", basedir);
                        if (!rmtree(basedir, true))
-                               fprintf(stderr, _("%s: failed to remove data directory\n"),
-                                               progname);
+                               pg_log_error("failed to remove data directory");
                }
                else if (found_existing_pgdata)
                {
-                       fprintf(stderr,
-                                       _("%s: removing contents of data directory \"%s\"\n"),
-                                       progname, basedir);
+                       pg_log_info("removing contents of data directory \"%s\"", basedir);
                        if (!rmtree(basedir, false))
-                               fprintf(stderr, _("%s: failed to remove contents of data directory\n"),
-                                               progname);
+                               pg_log_error("failed to remove contents of data directory");
                }
 
                if (made_new_xlogdir)
                {
-                       fprintf(stderr, _("%s: removing WAL directory \"%s\"\n"),
-                                       progname, xlog_dir);
+                       pg_log_info("removing WAL directory \"%s\"", xlog_dir);
                        if (!rmtree(xlog_dir, true))
-                               fprintf(stderr, _("%s: failed to remove WAL directory\n"),
-                                               progname);
+                               pg_log_error("failed to remove WAL directory");
                }
                else if (found_existing_xlogdir)
                {
-                       fprintf(stderr,
-                                       _("%s: removing contents of WAL directory \"%s\"\n"),
-                                       progname, xlog_dir);
+                       pg_log_info("removing contents of WAL directory \"%s\"", xlog_dir);
                        if (!rmtree(xlog_dir, false))
-                               fprintf(stderr, _("%s: failed to remove contents of WAL directory\n"),
-                                               progname);
+                               pg_log_error("failed to remove contents of WAL directory");
                }
        }
        else
        {
                if ((made_new_pgdata || found_existing_pgdata) && !checksum_failure)
-                       fprintf(stderr,
-                                       _("%s: data directory \"%s\" not removed at user's request\n"),
-                                       progname, basedir);
+                       pg_log_info("data directory \"%s\" not removed at user's request", basedir);
 
                if (made_new_xlogdir || found_existing_xlogdir)
-                       fprintf(stderr,
-                                       _("%s: WAL directory \"%s\" not removed at user's request\n"),
-                                       progname, xlog_dir);
+                       pg_log_info("WAL directory \"%s\" not removed at user's request", xlog_dir);
        }
 
        if ((made_tablespace_dirs || found_tablespace_dirs) && !checksum_failure)
-               fprintf(stderr,
-                               _("%s: changes to tablespace directories will not be undone\n"),
-                               progname);
+               pg_log_info("changes to tablespace directories will not be undone");
 }
 
 static void
@@ -258,7 +243,7 @@ tablespace_list_append(const char *arg)
        {
                if (dst_ptr - dst >= MAXPGPATH)
                {
-                       fprintf(stderr, _("%s: directory name too long\n"), progname);
+                       pg_log_error("directory name too long");
                        exit(1);
                }
 
@@ -268,7 +253,7 @@ tablespace_list_append(const char *arg)
                {
                        if (*cell->new_dir)
                        {
-                               fprintf(stderr, _("%s: multiple \"=\" signs in tablespace mapping\n"), progname);
+                               pg_log_error("multiple \"=\" signs in tablespace mapping");
                                exit(1);
                        }
                        else
@@ -280,9 +265,7 @@ tablespace_list_append(const char *arg)
 
        if (!*cell->old_dir || !*cell->new_dir)
        {
-               fprintf(stderr,
-                               _("%s: invalid tablespace mapping format \"%s\", must be \"OLDDIR=NEWDIR\"\n"),
-                               progname, arg);
+               pg_log_error("invalid tablespace mapping format \"%s\", must be \"OLDDIR=NEWDIR\"", arg);
                exit(1);
        }
 
@@ -294,15 +277,15 @@ tablespace_list_append(const char *arg)
         */
        if (!is_absolute_path(cell->old_dir))
        {
-               fprintf(stderr, _("%s: old directory is not an absolute path in tablespace mapping: %s\n"),
-                               progname, cell->old_dir);
+               pg_log_error("old directory is not an absolute path in tablespace mapping: %s",
+                                        cell->old_dir);
                exit(1);
        }
 
        if (!is_absolute_path(cell->new_dir))
        {
-               fprintf(stderr, _("%s: new directory is not an absolute path in tablespace mapping: %s\n"),
-                               progname, cell->new_dir);
+               pg_log_error("new directory is not an absolute path in tablespace mapping: %s",
+                                        cell->new_dir);
                exit(1);
        }
 
@@ -425,16 +408,14 @@ reached_end_position(XLogRecPtr segendpos, uint32 timeline,
                        r = read(bgpipe[0], xlogend, sizeof(xlogend) - 1);
                        if (r < 0)
                        {
-                               fprintf(stderr, _("%s: could not read from ready pipe: %s\n"),
-                                               progname, strerror(errno));
+                               pg_log_error("could not read from ready pipe: %m");
                                exit(1);
                        }
 
                        if (sscanf(xlogend, "%X/%X", &hi, &lo) != 2)
                        {
-                               fprintf(stderr,
-                                               _("%s: could not parse write-ahead log location \"%s\"\n"),
-                                               progname, xlogend);
+                               pg_log_error("could not parse write-ahead log location \"%s\"",
+                                                        xlogend);
                                exit(1);
                        }
                        xlogendptr = ((uint64) hi) << 32 | lo;
@@ -526,9 +507,7 @@ LogStreamerMain(logstreamer_param *param)
 
        if (!stream.walmethod->finish())
        {
-               fprintf(stderr,
-                               _("%s: could not finish writing WAL files: %s\n"),
-                               progname, strerror(errno));
+               pg_log_error("could not finish writing WAL files: %m");
                return 1;
        }
 
@@ -563,9 +542,8 @@ StartLogStreamer(char *startpos, uint32 timeline, char *sysidentifier)
        /* Convert the starting position */
        if (sscanf(startpos, "%X/%X", &hi, &lo) != 2)
        {
-               fprintf(stderr,
-                               _("%s: could not parse write-ahead log location \"%s\"\n"),
-                               progname, startpos);
+               pg_log_error("could not parse write-ahead log location \"%s\"",
+                                        startpos);
                exit(1);
        }
        param->startptr = ((uint64) hi) << 32 | lo;
@@ -576,9 +554,7 @@ StartLogStreamer(char *startpos, uint32 timeline, char *sysidentifier)
        /* Create our background pipe */
        if (pipe(bgpipe) < 0)
        {
-               fprintf(stderr,
-                               _("%s: could not create pipe for background process: %s\n"),
-                               progname, strerror(errno));
+               pg_log_error("could not create pipe for background process: %m");
                exit(1);
        }
 #endif
@@ -613,11 +589,11 @@ StartLogStreamer(char *startpos, uint32 timeline, char *sysidentifier)
                if (verbose)
                {
                        if (temp_replication_slot)
-                               fprintf(stderr, _("%s: created temporary replication slot \"%s\"\n"),
-                                               progname, replication_slot);
+                               pg_log_info("created temporary replication slot \"%s\"",
+                                                       replication_slot);
                        else
-                               fprintf(stderr, _("%s: created replication slot \"%s\"\n"),
-                                               progname, replication_slot);
+                               pg_log_info("created replication slot \"%s\"",
+                                                       replication_slot);
                }
        }
 
@@ -636,9 +612,7 @@ StartLogStreamer(char *startpos, uint32 timeline, char *sysidentifier)
 
                if (pg_mkdir_p(statusdir, pg_dir_create_mode) != 0 && errno != EEXIST)
                {
-                       fprintf(stderr,
-                                       _("%s: could not create directory \"%s\": %s\n"),
-                                       progname, statusdir, strerror(errno));
+                       pg_log_error("could not create directory \"%s\": %m", statusdir);
                        exit(1);
                }
        }
@@ -656,8 +630,7 @@ StartLogStreamer(char *startpos, uint32 timeline, char *sysidentifier)
        }
        else if (bgchild < 0)
        {
-               fprintf(stderr, _("%s: could not create background process: %s\n"),
-                               progname, strerror(errno));
+               pg_log_error("could not create background process: %m");
                exit(1);
        }
 
@@ -669,8 +642,7 @@ StartLogStreamer(char *startpos, uint32 timeline, char *sysidentifier)
        bgchild = _beginthreadex(NULL, 0, (void *) LogStreamerMain, param, 0, NULL);
        if (bgchild == 0)
        {
-               fprintf(stderr, _("%s: could not create background thread: %s\n"),
-                               progname, strerror(errno));
+               pg_log_error("could not create background thread: %m");
                exit(1);
        }
 #endif
@@ -693,9 +665,7 @@ verify_dir_is_empty_or_create(char *dirname, bool *created, bool *found)
                         */
                        if (pg_mkdir_p(dirname, pg_dir_create_mode) == -1)
                        {
-                               fprintf(stderr,
-                                               _("%s: could not create directory \"%s\": %s\n"),
-                                               progname, dirname, strerror(errno));
+                               pg_log_error("could not create directory \"%s\": %m", dirname);
                                exit(1);
                        }
                        if (created)
@@ -716,17 +686,14 @@ verify_dir_is_empty_or_create(char *dirname, bool *created, bool *found)
                        /*
                         * Exists, not empty
                         */
-                       fprintf(stderr,
-                                       _("%s: directory \"%s\" exists but is not empty\n"),
-                                       progname, dirname);
+                       pg_log_error("directory \"%s\" exists but is not empty", dirname);
                        exit(1);
                case -1:
 
                        /*
                         * Access problem
                         */
-                       fprintf(stderr, _("%s: could not access directory \"%s\": %s\n"),
-                                       progname, dirname, strerror(errno));
+                       pg_log_error("could not access directory \"%s\": %m", dirname);
                        exit(1);
        }
 }
@@ -839,16 +806,12 @@ parse_max_rate(char *src)
        result = strtod(src, &after_num);
        if (src == after_num)
        {
-               fprintf(stderr,
-                               _("%s: transfer rate \"%s\" is not a valid value\n"),
-                               progname, src);
+               pg_log_error("transfer rate \"%s\" is not a valid value", src);
                exit(1);
        }
        if (errno != 0)
        {
-               fprintf(stderr,
-                               _("%s: invalid transfer rate \"%s\": %s\n"),
-                               progname, src, strerror(errno));
+               pg_log_error("invalid transfer rate \"%s\": %m", src);
                exit(1);
        }
 
@@ -857,8 +820,7 @@ parse_max_rate(char *src)
                /*
                 * Reject obviously wrong values here.
                 */
-               fprintf(stderr, _("%s: transfer rate must be greater than zero\n"),
-                               progname);
+               pg_log_error("transfer rate must be greater than zero");
                exit(1);
        }
 
@@ -890,18 +852,14 @@ parse_max_rate(char *src)
 
        if (*after_num != '\0')
        {
-               fprintf(stderr,
-                               _("%s: invalid --max-rate unit: \"%s\"\n"),
-                               progname, suffix);
+               pg_log_error("invalid --max-rate unit: \"%s\"", suffix);
                exit(1);
        }
 
        /* Valid integer? */
        if ((uint64) result != (uint64) ((uint32) result))
        {
-               fprintf(stderr,
-                               _("%s: transfer rate \"%s\" exceeds integer range\n"),
-                               progname, src);
+               pg_log_error("transfer rate \"%s\" exceeds integer range", src);
                exit(1);
        }
 
@@ -911,9 +869,7 @@ parse_max_rate(char *src)
         */
        if (result < MAX_RATE_LOWER || result > MAX_RATE_UPPER)
        {
-               fprintf(stderr,
-                               _("%s: transfer rate \"%s\" is out of range\n"),
-                               progname, src);
+               pg_log_error("transfer rate \"%s\" is out of range", src);
                exit(1);
        }
 
@@ -935,9 +891,8 @@ writeTarData(
        {
                if (gzwrite(ztarfile, buf, r) != r)
                {
-                       fprintf(stderr,
-                                       _("%s: could not write to compressed file \"%s\": %s\n"),
-                                       progname, current_file, get_gz_error(ztarfile));
+                       pg_log_error("could not write to compressed file \"%s\": %s",
+                                                current_file, get_gz_error(ztarfile));
                        exit(1);
                }
        }
@@ -946,8 +901,7 @@ writeTarData(
        {
                if (fwrite(buf, r, 1, tarfile) != 1)
                {
-                       fprintf(stderr, _("%s: could not write to file \"%s\": %s\n"),
-                                       progname, current_file, strerror(errno));
+                       pg_log_error("could not write to file \"%s\": %m", current_file);
                        exit(1);
                }
        }
@@ -1012,9 +966,8 @@ ReceiveTarFile(PGconn *conn, PGresult *res, int rownum)
                                if (gzsetparams(ztarfile, compresslevel,
                                                                Z_DEFAULT_STRATEGY) != Z_OK)
                                {
-                                       fprintf(stderr,
-                                                       _("%s: could not set compression level %d: %s\n"),
-                                                       progname, compresslevel, get_gz_error(ztarfile));
+                                       pg_log_error("could not set compression level %d: %s",
+                                                                compresslevel, get_gz_error(ztarfile));
                                        exit(1);
                                }
                        }
@@ -1033,9 +986,8 @@ ReceiveTarFile(PGconn *conn, PGresult *res, int rownum)
                                if (gzsetparams(ztarfile, compresslevel,
                                                                Z_DEFAULT_STRATEGY) != Z_OK)
                                {
-                                       fprintf(stderr,
-                                                       _("%s: could not set compression level %d: %s\n"),
-                                                       progname, compresslevel, get_gz_error(ztarfile));
+                                       pg_log_error("could not set compression level %d: %s",
+                                                                compresslevel, get_gz_error(ztarfile));
                                        exit(1);
                                }
                        }
@@ -1061,9 +1013,8 @@ ReceiveTarFile(PGconn *conn, PGresult *res, int rownum)
                        if (gzsetparams(ztarfile, compresslevel,
                                                        Z_DEFAULT_STRATEGY) != Z_OK)
                        {
-                               fprintf(stderr,
-                                               _("%s: could not set compression level %d: %s\n"),
-                                               progname, compresslevel, get_gz_error(ztarfile));
+                               pg_log_error("could not set compression level %d: %s",
+                                                        compresslevel, get_gz_error(ztarfile));
                                exit(1);
                        }
                }
@@ -1082,9 +1033,8 @@ ReceiveTarFile(PGconn *conn, PGresult *res, int rownum)
                if (!ztarfile)
                {
                        /* Compression is in use */
-                       fprintf(stderr,
-                                       _("%s: could not create compressed file \"%s\": %s\n"),
-                                       progname, filename, get_gz_error(ztarfile));
+                       pg_log_error("could not create compressed file \"%s\": %s",
+                                                filename, get_gz_error(ztarfile));
                        exit(1);
                }
        }
@@ -1094,8 +1044,7 @@ ReceiveTarFile(PGconn *conn, PGresult *res, int rownum)
                /* Either no zlib support, or zlib support but compresslevel = 0 */
                if (!tarfile)
                {
-                       fprintf(stderr, _("%s: could not create file \"%s\": %s\n"),
-                                       progname, filename, strerror(errno));
+                       pg_log_error("could not create file \"%s\": %m", filename);
                        exit(1);
                }
        }
@@ -1106,8 +1055,8 @@ ReceiveTarFile(PGconn *conn, PGresult *res, int rownum)
        res = PQgetResult(conn);
        if (PQresultStatus(res) != PGRES_COPY_OUT)
        {
-               fprintf(stderr, _("%s: could not get COPY data stream: %s"),
-                               progname, PQerrorMessage(conn));
+               pg_log_error("could not get COPY data stream: %s",
+                                        PQerrorMessage(conn));
                exit(1);
        }
 
@@ -1191,9 +1140,8 @@ ReceiveTarFile(PGconn *conn, PGresult *res, int rownum)
                        {
                                if (gzclose(ztarfile) != 0)
                                {
-                                       fprintf(stderr,
-                                                       _("%s: could not close compressed file \"%s\": %s\n"),
-                                                       progname, filename, get_gz_error(ztarfile));
+                                       pg_log_error("could not close compressed file \"%s\": %s",
+                                                                filename, get_gz_error(ztarfile));
                                        exit(1);
                                }
                        }
@@ -1204,9 +1152,8 @@ ReceiveTarFile(PGconn *conn, PGresult *res, int rownum)
                                {
                                        if (fclose(tarfile) != 0)
                                        {
-                                               fprintf(stderr,
-                                                               _("%s: could not close file \"%s\": %s\n"),
-                                                               progname, filename, strerror(errno));
+                                               pg_log_error("could not close file \"%s\": %m",
+                                                                        filename);
                                                exit(1);
                                        }
                                }
@@ -1216,8 +1163,8 @@ ReceiveTarFile(PGconn *conn, PGresult *res, int rownum)
                }
                else if (r == -2)
                {
-                       fprintf(stderr, _("%s: could not read COPY data: %s"),
-                                       progname, PQerrorMessage(conn));
+                       pg_log_error("could not read COPY data: %s",
+                                                PQerrorMessage(conn));
                        exit(1);
                }
 
@@ -1401,7 +1348,7 @@ ReceiveTarFile(PGconn *conn, PGresult *res, int rownum)
 
        /* sync the resulting tar file, errors are not considered fatal */
        if (do_sync && strcmp(basedir, "-") != 0)
-               (void) fsync_fname(filename, false, progname);
+               (void) fsync_fname(filename, false);
 }
 
 
@@ -1462,8 +1409,8 @@ ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res, int rownum)
        res = PQgetResult(conn);
        if (PQresultStatus(res) != PGRES_COPY_OUT)
        {
-               fprintf(stderr, _("%s: could not get COPY data stream: %s"),
-                               progname, PQerrorMessage(conn));
+               pg_log_error("could not get COPY data stream: %s",
+                                        PQerrorMessage(conn));
                exit(1);
        }
 
@@ -1491,8 +1438,8 @@ ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res, int rownum)
                }
                else if (r == -2)
                {
-                       fprintf(stderr, _("%s: could not read COPY data: %s"),
-                                       progname, PQerrorMessage(conn));
+                       pg_log_error("could not read COPY data: %s",
+                                                PQerrorMessage(conn));
                        exit(1);
                }
 
@@ -1505,8 +1452,7 @@ ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res, int rownum)
                         */
                        if (r != 512)
                        {
-                               fprintf(stderr, _("%s: invalid tar block header size: %d\n"),
-                                               progname, r);
+                               pg_log_error("invalid tar block header size: %d", r);
                                exit(1);
                        }
                        totaldone += 512;
@@ -1554,17 +1500,15 @@ ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res, int rownum)
                                                           pg_str_endswith(filename, "/archive_status")) &&
                                                          errno == EEXIST))
                                                {
-                                                       fprintf(stderr,
-                                                                       _("%s: could not create directory \"%s\": %s\n"),
-                                                                       progname, filename, strerror(errno));
+                                                       pg_log_error("could not create directory \"%s\": %m",
+                                                                                filename);
                                                        exit(1);
                                                }
                                        }
 #ifndef WIN32
                                        if (chmod(filename, (mode_t) filemode))
-                                               fprintf(stderr,
-                                                               _("%s: could not set permissions on directory \"%s\": %s\n"),
-                                                               progname, filename, strerror(errno));
+                                               pg_log_error("could not set permissions on directory \"%s\": %m",
+                                                                        filename);
 #endif
                                }
                                else if (copybuf[156] == '2')
@@ -1586,18 +1530,15 @@ ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res, int rownum)
                                        mapped_tblspc_path = get_tablespace_mapping(&copybuf[157]);
                                        if (symlink(mapped_tblspc_path, filename) != 0)
                                        {
-                                               fprintf(stderr,
-                                                               _("%s: could not create symbolic link from \"%s\" to \"%s\": %s\n"),
-                                                               progname, filename, mapped_tblspc_path,
-                                                               strerror(errno));
+                                               pg_log_error("could not create symbolic link from \"%s\" to \"%s\": %m",
+                                                                        filename, mapped_tblspc_path);
                                                exit(1);
                                        }
                                }
                                else
                                {
-                                       fprintf(stderr,
-                                                       _("%s: unrecognized link indicator \"%c\"\n"),
-                                                       progname, copybuf[156]);
+                                       pg_log_error("unrecognized link indicator \"%c\"",
+                                                                copybuf[156]);
                                        exit(1);
                                }
                                continue;               /* directory or link handled */
@@ -1609,15 +1550,14 @@ ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res, int rownum)
                        file = fopen(filename, "wb");
                        if (!file)
                        {
-                               fprintf(stderr, _("%s: could not create file \"%s\": %s\n"),
-                                               progname, filename, strerror(errno));
+                               pg_log_error("could not create file \"%s\": %m", filename);
                                exit(1);
                        }
 
 #ifndef WIN32
                        if (chmod(filename, (mode_t) filemode))
-                               fprintf(stderr, _("%s: could not set permissions on file \"%s\": %s\n"),
-                                               progname, filename, strerror(errno));
+                               pg_log_error("could not set permissions on file \"%s\": %m",
+                                                        filename);
 #endif
 
                        if (current_len_left == 0)
@@ -1649,8 +1589,7 @@ ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res, int rownum)
 
                        if (fwrite(copybuf, r, 1, file) != 1)
                        {
-                               fprintf(stderr, _("%s: could not write to file \"%s\": %s\n"),
-                                               progname, filename, strerror(errno));
+                               pg_log_error("could not write to file \"%s\": %m", filename);
                                exit(1);
                        }
                        totaldone += r;
@@ -1674,9 +1613,7 @@ ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res, int rownum)
 
        if (file != NULL)
        {
-               fprintf(stderr,
-                               _("%s: COPY stream ended before last file was finished\n"),
-                               progname);
+               pg_log_error("COPY stream ended before last file was finished");
                exit(1);
        }
 
@@ -1703,7 +1640,7 @@ escape_quotes(const char *src)
 
        if (!result)
        {
-               fprintf(stderr, _("%s: out of memory\n"), progname);
+               pg_log_error("out of memory");
                exit(1);
        }
        return result;
@@ -1723,7 +1660,7 @@ GenerateRecoveryConf(PGconn *conn)
        recoveryconfcontents = createPQExpBuffer();
        if (!recoveryconfcontents)
        {
-               fprintf(stderr, _("%s: out of memory\n"), progname);
+               pg_log_error("out of memory");
                exit(1);
        }
 
@@ -1737,7 +1674,7 @@ GenerateRecoveryConf(PGconn *conn)
        connOptions = PQconninfo(conn);
        if (connOptions == NULL)
        {
-               fprintf(stderr, _("%s: out of memory\n"), progname);
+               pg_log_error("out of memory");
                exit(1);
        }
 
@@ -1788,7 +1725,7 @@ GenerateRecoveryConf(PGconn *conn)
        if (PQExpBufferBroken(recoveryconfcontents) ||
                PQExpBufferDataBroken(conninfo_buf))
        {
-               fprintf(stderr, _("%s: out of memory\n"), progname);
+               pg_log_error("out of memory");
                exit(1);
        }
 
@@ -1821,16 +1758,13 @@ WriteRecoveryConf(void)
        cf = fopen(filename, is_recovery_guc_supported ? "a" : "w");
        if (cf == NULL)
        {
-               fprintf(stderr, _("%s: could not open file \"%s\": %s\n"),
-                               progname, filename, strerror(errno));
+               pg_log_error("could not open file \"%s\": %m", filename);
                exit(1);
        }
 
        if (fwrite(recoveryconfcontents->data, recoveryconfcontents->len, 1, cf) != 1)
        {
-               fprintf(stderr,
-                               _("%s: could not write to file \"%s\": %s\n"),
-                               progname, filename, strerror(errno));
+               pg_log_error("could not write to file \"%s\": %m", filename);
                exit(1);
        }
 
@@ -1842,7 +1776,7 @@ WriteRecoveryConf(void)
                cf = fopen(filename, "w");
                if (cf == NULL)
                {
-                       fprintf(stderr, _("%s: could not create file \"%s\": %s\n"), progname, filename, strerror(errno));
+                       pg_log_error("could not create file \"%s\": %m", filename);
                        exit(1);
                }
 
@@ -1883,8 +1817,8 @@ BaseBackup(void)
        {
                const char *serverver = PQparameterStatus(conn, "server_version");
 
-               fprintf(stderr, _("%s: incompatible server version %s\n"),
-                               progname, serverver ? serverver : "'unknown'");
+               pg_log_error("incompatible server version %s",
+                                        serverver ? serverver : "'unknown'");
                exit(1);
        }
 
@@ -1898,7 +1832,7 @@ BaseBackup(void)
                 * Error message already written in CheckServerVersionForStreaming(),
                 * but add a hint about using -X none.
                 */
-               fprintf(stderr, _("HINT: use -X none or -X fetch to disable log streaming\n"));
+               pg_log_info("HINT: use -X none or -X fetch to disable log streaming");
                exit(1);
        }
 
@@ -1923,9 +1857,7 @@ BaseBackup(void)
                maxrate_clause = psprintf("MAX_RATE %u", maxrate);
 
        if (verbose)
-               fprintf(stderr,
-                               _("%s: initiating base backup, waiting for checkpoint to complete\n"),
-                               progname);
+               pg_log_info("initiating base backup, waiting for checkpoint to complete");
 
        if (showprogress && !verbose)
        {
@@ -1949,8 +1881,8 @@ BaseBackup(void)
 
        if (PQsendQuery(conn, basebkp) == 0)
        {
-               fprintf(stderr, _("%s: could not send replication command \"%s\": %s"),
-                               progname, "BASE_BACKUP", PQerrorMessage(conn));
+               pg_log_error("could not send replication command \"%s\": %s",
+                                        "BASE_BACKUP", PQerrorMessage(conn));
                exit(1);
        }
 
@@ -1960,22 +1892,21 @@ BaseBackup(void)
        res = PQgetResult(conn);
        if (PQresultStatus(res) != PGRES_TUPLES_OK)
        {
-               fprintf(stderr, _("%s: could not initiate base backup: %s"),
-                               progname, PQerrorMessage(conn));
+               pg_log_error("could not initiate base backup: %s",
+                                        PQerrorMessage(conn));
                exit(1);
        }
        if (PQntuples(res) != 1)
        {
-               fprintf(stderr,
-                               _("%s: server returned unexpected response to BASE_BACKUP command; got %d rows and %d fields, expected %d rows and %d fields\n"),
-                               progname, PQntuples(res), PQnfields(res), 1, 2);
+               pg_log_error("server returned unexpected response to BASE_BACKUP command; got %d rows and %d fields, expected %d rows and %d fields",
+                                        PQntuples(res), PQnfields(res), 1, 2);
                exit(1);
        }
 
        strlcpy(xlogstart, PQgetvalue(res, 0, 0), sizeof(xlogstart));
 
        if (verbose)
-               fprintf(stderr, _("%s: checkpoint completed\n"), progname);
+               pg_log_info("checkpoint completed");
 
        /*
         * 9.3 and later sends the TLI of the starting point. With older servers,
@@ -1990,8 +1921,8 @@ BaseBackup(void)
        MemSet(xlogend, 0, sizeof(xlogend));
 
        if (verbose && includewal != NO_WAL)
-               fprintf(stderr, _("%s: write-ahead log start point: %s on timeline %u\n"),
-                               progname, xlogstart, starttli);
+               pg_log_info("write-ahead log start point: %s on timeline %u",
+                                       xlogstart, starttli);
 
        /*
         * Get the header
@@ -1999,13 +1930,13 @@ BaseBackup(void)
        res = PQgetResult(conn);
        if (PQresultStatus(res) != PGRES_TUPLES_OK)
        {
-               fprintf(stderr, _("%s: could not get backup header: %s"),
-                               progname, PQerrorMessage(conn));
+               pg_log_error("could not get backup header: %s",
+                                        PQerrorMessage(conn));
                exit(1);
        }
        if (PQntuples(res) < 1)
        {
-               fprintf(stderr, _("%s: no data returned from server\n"), progname);
+               pg_log_error("no data returned from server");
                exit(1);
        }
 
@@ -2036,9 +1967,8 @@ BaseBackup(void)
         */
        if (format == 't' && strcmp(basedir, "-") == 0 && PQntuples(res) > 1)
        {
-               fprintf(stderr,
-                               _("%s: can only write single tablespace to stdout, database has %d\n"),
-                               progname, PQntuples(res));
+               pg_log_error("can only write single tablespace to stdout, database has %d",
+                                        PQntuples(res));
                exit(1);
        }
 
@@ -2049,8 +1979,7 @@ BaseBackup(void)
        if (includewal == STREAM_WAL)
        {
                if (verbose)
-                       fprintf(stderr, _("%s: starting background WAL receiver\n"),
-                                       progname);
+                       pg_log_info("starting background WAL receiver");
                StartLogStreamer(xlogstart, starttli, sysidentifier);
        }
 
@@ -2080,21 +2009,18 @@ BaseBackup(void)
        res = PQgetResult(conn);
        if (PQresultStatus(res) != PGRES_TUPLES_OK)
        {
-               fprintf(stderr,
-                               _("%s: could not get write-ahead log end position from server: %s"),
-                               progname, PQerrorMessage(conn));
+               pg_log_error("could not get write-ahead log end position from server: %s",
+                                        PQerrorMessage(conn));
                exit(1);
        }
        if (PQntuples(res) != 1)
        {
-               fprintf(stderr,
-                               _("%s: no write-ahead log end position returned from server\n"),
-                               progname);
+               pg_log_error("no write-ahead log end position returned from server");
                exit(1);
        }
        strlcpy(xlogend, PQgetvalue(res, 0, 0), sizeof(xlogend));
        if (verbose && includewal != NO_WAL)
-               fprintf(stderr, _("%s: write-ahead log end point: %s\n"), progname, xlogend);
+               pg_log_info("write-ahead log end point: %s", xlogend);
        PQclear(res);
 
        res = PQgetResult(conn);
@@ -2105,14 +2031,13 @@ BaseBackup(void)
                if (sqlstate &&
                        strcmp(sqlstate, ERRCODE_DATA_CORRUPTED) == 0)
                {
-                       fprintf(stderr, _("%s: checksum error occurred\n"),
-                                       progname);
+                       pg_log_error("checksum error occurred");
                        checksum_failure = true;
                }
                else
                {
-                       fprintf(stderr, _("%s: final receive failed: %s"),
-                                       progname, PQerrorMessage(conn));
+                       pg_log_error("final receive failed: %s",
+                                                PQerrorMessage(conn));
                }
                exit(1);
        }
@@ -2135,15 +2060,12 @@ BaseBackup(void)
 #endif
 
                if (verbose)
-                       fprintf(stderr,
-                                       _("%s: waiting for background process to finish streaming ...\n"), progname);
+                       pg_log_info("waiting for background process to finish streaming ...");
 
 #ifndef WIN32
                if (write(bgpipe[1], xlogend, strlen(xlogend)) != strlen(xlogend))
                {
-                       fprintf(stderr,
-                                       _("%s: could not send command to background pipe: %s\n"),
-                                       progname, strerror(errno));
+                       pg_log_info("could not send command to background pipe: %m");
                        exit(1);
                }
 
@@ -2151,20 +2073,17 @@ BaseBackup(void)
                r = waitpid(bgchild, &status, 0);
                if (r == (pid_t) -1)
                {
-                       fprintf(stderr, _("%s: could not wait for child process: %s\n"),
-                                       progname, strerror(errno));
+                       pg_log_error("could not wait for child process: %m");
                        exit(1);
                }
                if (r != bgchild)
                {
-                       fprintf(stderr, _("%s: child %d died, expected %d\n"),
-                                       progname, (int) r, (int) bgchild);
+                       pg_log_error("child %d died, expected %d", (int) r, (int) bgchild);
                        exit(1);
                }
                if (status != 0)
                {
-                       fprintf(stderr, "%s: %s\n",
-                                       progname, wait_result_to_str(status));
+                       pg_log_error("%s", wait_result_to_str(status));
                        exit(1);
                }
                /* Exited normally, we're happy! */
@@ -2177,9 +2096,8 @@ BaseBackup(void)
                 */
                if (sscanf(xlogend, "%X/%X", &hi, &lo) != 2)
                {
-                       fprintf(stderr,
-                                       _("%s: could not parse write-ahead log location \"%s\"\n"),
-                                       progname, xlogend);
+                       pg_log_error("could not parse write-ahead log location \"%s\"",
+                                                xlogend);
                        exit(1);
                }
                xlogendptr = ((uint64) hi) << 32 | lo;
@@ -2190,21 +2108,19 @@ BaseBackup(void)
                        WAIT_OBJECT_0)
                {
                        _dosmaperr(GetLastError());
-                       fprintf(stderr, _("%s: could not wait for child thread: %s\n"),
-                                       progname, strerror(errno));
+                       pg_log_error("could not wait for child thread: %m");
                        exit(1);
                }
                if (GetExitCodeThread((HANDLE) bgchild_handle, &status) == 0)
                {
                        _dosmaperr(GetLastError());
-                       fprintf(stderr, _("%s: could not get child thread exit status: %s\n"),
-                                       progname, strerror(errno));
+                       pg_log_error("could not get child thread exit status: %m");
                        exit(1);
                }
                if (status != 0)
                {
-                       fprintf(stderr, _("%s: child thread exited with error %u\n"),
-                                       progname, (unsigned int) status);
+                       pg_log_error("child thread exited with error %u",
+                                                (unsigned int) status);
                        exit(1);
                }
                /* Exited normally, we're happy */
@@ -2231,21 +2147,20 @@ BaseBackup(void)
        if (do_sync)
        {
                if (verbose)
-                       fprintf(stderr,
-                                       _("%s: syncing data to disk ...\n"), progname);
+                       pg_log_info("syncing data to disk ...");
                if (format == 't')
                {
                        if (strcmp(basedir, "-") != 0)
-                               (void) fsync_fname(basedir, true, progname);
+                               (void) fsync_fname(basedir, true);
                }
                else
                {
-                       (void) fsync_pgdata(basedir, progname, serverVersion);
+                       (void) fsync_pgdata(basedir, serverVersion);
                }
        }
 
        if (verbose)
-               fprintf(stderr, _("%s: base backup completed\n"), progname);
+               pg_log_info("base backup completed");
 }
 
 
@@ -2287,6 +2202,7 @@ main(int argc, char **argv)
 
        int                     option_index;
 
+       pg_logging_init(argv[0]);
        progname = get_progname(argv[0]);
        set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_basebackup"));
 
@@ -2325,9 +2241,8 @@ main(int argc, char **argv)
                                        format = 't';
                                else
                                {
-                                       fprintf(stderr,
-                                                       _("%s: invalid output format \"%s\", must be \"plain\" or \"tar\"\n"),
-                                                       progname, optarg);
+                                       pg_log_error("invalid output format \"%s\", must be \"plain\" or \"tar\"\n",
+                                                                optarg);
                                        exit(1);
                                }
                                break;
@@ -2370,9 +2285,8 @@ main(int argc, char **argv)
                                }
                                else
                                {
-                                       fprintf(stderr,
-                                                       _("%s: invalid wal-method option \"%s\", must be \"fetch\", \"stream\", or \"none\"\n"),
-                                                       progname, optarg);
+                                       pg_log_error("invalid wal-method option \"%s\", must be \"fetch\", \"stream\", or \"none\"",
+                                                                optarg);
                                        exit(1);
                                }
                                break;
@@ -2399,8 +2313,7 @@ main(int argc, char **argv)
                                compresslevel = atoi(optarg);
                                if (compresslevel < 0 || compresslevel > 9)
                                {
-                                       fprintf(stderr, _("%s: invalid compression level \"%s\"\n"),
-                                                       progname, optarg);
+                                       pg_log_error("invalid compression level \"%s\"\n", optarg);
                                        exit(1);
                                }
                                break;
@@ -2411,8 +2324,8 @@ main(int argc, char **argv)
                                        fastcheckpoint = false;
                                else
                                {
-                                       fprintf(stderr, _("%s: invalid checkpoint argument \"%s\", must be \"fast\" or \"spread\"\n"),
-                                                       progname, optarg);
+                                       pg_log_error("invalid checkpoint argument \"%s\", must be \"fast\" or \"spread\"",
+                                                                optarg);
                                        exit(1);
                                }
                                break;
@@ -2438,8 +2351,7 @@ main(int argc, char **argv)
                                standby_message_timeout = atoi(optarg) * 1000;
                                if (standby_message_timeout < 0)
                                {
-                                       fprintf(stderr, _("%s: invalid status interval \"%s\"\n"),
-                                                       progname, optarg);
+                                       pg_log_error("invalid status interval \"%s\"", optarg);
                                        exit(1);
                                }
                                break;
@@ -2468,9 +2380,8 @@ main(int argc, char **argv)
         */
        if (optind < argc)
        {
-               fprintf(stderr,
-                               _("%s: too many command-line arguments (first is \"%s\")\n"),
-                               progname, argv[optind]);
+               pg_log_error("too many command-line arguments (first is \"%s\")",
+                                        argv[optind]);
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                progname);
                exit(1);
@@ -2481,7 +2392,7 @@ main(int argc, char **argv)
         */
        if (basedir == NULL)
        {
-               fprintf(stderr, _("%s: no target directory specified\n"), progname);
+               pg_log_error("no target directory specified");
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                progname);
                exit(1);
@@ -2492,9 +2403,7 @@ main(int argc, char **argv)
         */
        if (format == 'p' && compresslevel != 0)
        {
-               fprintf(stderr,
-                               _("%s: only tar mode backups can be compressed\n"),
-                               progname);
+               pg_log_error("only tar mode backups can be compressed");
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                progname);
                exit(1);
@@ -2502,9 +2411,7 @@ main(int argc, char **argv)
 
        if (format == 't' && includewal == STREAM_WAL && strcmp(basedir, "-") == 0)
        {
-               fprintf(stderr,
-                               _("%s: cannot stream write-ahead logs in tar mode to stdout\n"),
-                               progname);
+               pg_log_error("cannot stream write-ahead logs in tar mode to stdout");
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                progname);
                exit(1);
@@ -2512,9 +2419,7 @@ main(int argc, char **argv)
 
        if (replication_slot && includewal != STREAM_WAL)
        {
-               fprintf(stderr,
-                               _("%s: replication slots can only be used with WAL streaming\n"),
-                               progname);
+               pg_log_error("replication slots can only be used with WAL streaming");
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                progname);
                exit(1);
@@ -2524,9 +2429,7 @@ main(int argc, char **argv)
        {
                if (replication_slot)
                {
-                       fprintf(stderr,
-                                       _("%s: --no-slot cannot be used with slot name\n"),
-                                       progname);
+                       pg_log_error("--no-slot cannot be used with slot name");
                        fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                        progname);
                        exit(1);
@@ -2538,9 +2441,8 @@ main(int argc, char **argv)
        {
                if (!replication_slot)
                {
-                       fprintf(stderr,
-                                       _("%s: %s needs a slot to be specified using --slot\n"),
-                                       progname, "--create-slot");
+                       pg_log_error("%s needs a slot to be specified using --slot",
+                                                "--create-slot");
                        fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                        progname);
                        exit(1);
@@ -2548,9 +2450,7 @@ main(int argc, char **argv)
 
                if (no_slot)
                {
-                       fprintf(stderr,
-                                       _("%s: --create-slot and --no-slot are incompatible options\n"),
-                                       progname);
+                       pg_log_error("--create-slot and --no-slot are incompatible options");
                        fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                        progname);
                        exit(1);
@@ -2561,9 +2461,7 @@ main(int argc, char **argv)
        {
                if (format != 'p')
                {
-                       fprintf(stderr,
-                                       _("%s: WAL directory location can only be specified in plain mode\n"),
-                                       progname);
+                       pg_log_error("WAL directory location can only be specified in plain mode");
                        fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                        progname);
                        exit(1);
@@ -2573,8 +2471,7 @@ main(int argc, char **argv)
                canonicalize_path(xlog_dir);
                if (!is_absolute_path(xlog_dir))
                {
-                       fprintf(stderr, _("%s: WAL directory location must be "
-                                                         "an absolute path\n"), progname);
+                       pg_log_error("WAL directory location must be an absolute path");
                        fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                        progname);
                        exit(1);
@@ -2584,9 +2481,7 @@ main(int argc, char **argv)
 #ifndef HAVE_LIBZ
        if (compresslevel != 0)
        {
-               fprintf(stderr,
-                               _("%s: this build does not support compression\n"),
-                               progname);
+               pg_log_error("this build does not support compression");
                exit(1);
        }
 #endif
@@ -2640,12 +2535,11 @@ main(int argc, char **argv)
 #ifdef HAVE_SYMLINK
                if (symlink(xlog_dir, linkloc) != 0)
                {
-                       fprintf(stderr, _("%s: could not create symbolic link \"%s\": %s\n"),
-                                       progname, linkloc, strerror(errno));
+                       pg_log_error("could not create symbolic link \"%s\": %m", linkloc);
                        exit(1);
                }
 #else
-               fprintf(stderr, _("%s: symlinks are not supported on this platform\n"), progname);
+               pg_log_error("symlinks are not supported on this platform");
                exit(1);
 #endif
                free(linkloc);
index aa114f1563de1a7744cf39093c986aff83adde5a..9e4d296129c521261f8e572ce5b3da48ddd1bd36 100644 (file)
@@ -20,6 +20,7 @@
 #include <unistd.h>
 
 #include "common/file_perm.h"
+#include "fe_utils/logging.h"
 #include "libpq-fe.h"
 #include "access/xlog_internal.h"
 #include "getopt_long.h"
@@ -114,16 +115,16 @@ stop_streaming(XLogRecPtr xlogpos, uint32 timeline, bool segment_finished)
 
        /* we assume that we get called once at the end of each segment */
        if (verbose && segment_finished)
-               fprintf(stderr, _("%s: finished segment at %X/%X (timeline %u)\n"),
-                               progname, (uint32) (xlogpos >> 32), (uint32) xlogpos,
-                               timeline);
+               pg_log_info("finished segment at %X/%X (timeline %u)",
+                                       (uint32) (xlogpos >> 32), (uint32) xlogpos,
+                                       timeline);
 
        if (!XLogRecPtrIsInvalid(endpos) && endpos < xlogpos)
        {
                if (verbose)
-                       fprintf(stderr, _("%s: stopped log streaming at %X/%X (timeline %u)\n"),
-                                       progname, (uint32) (xlogpos >> 32), (uint32) xlogpos,
-                                       timeline);
+                       pg_log_info("stopped log streaming at %X/%X (timeline %u)",
+                                               (uint32) (xlogpos >> 32), (uint32) xlogpos,
+                                               timeline);
                time_to_stop = true;
                return true;
        }
@@ -137,9 +138,9 @@ stop_streaming(XLogRecPtr xlogpos, uint32 timeline, bool segment_finished)
         * timeline, but it's close enough for reporting purposes.
         */
        if (verbose && prevtimeline != 0 && prevtimeline != timeline)
-               fprintf(stderr, _("%s: switched to timeline %u at %X/%X\n"),
-                               progname, timeline,
-                               (uint32) (prevpos >> 32), (uint32) prevpos);
+               pg_log_info("switched to timeline %u at %X/%X",
+                                       timeline,
+                                       (uint32) (prevpos >> 32), (uint32) prevpos);
 
        prevtimeline = timeline;
        prevpos = xlogpos;
@@ -147,8 +148,7 @@ stop_streaming(XLogRecPtr xlogpos, uint32 timeline, bool segment_finished)
        if (time_to_stop)
        {
                if (verbose)
-                       fprintf(stderr, _("%s: received interrupt signal, exiting\n"),
-                                       progname);
+                       pg_log_info("received interrupt signal, exiting");
                return true;
        }
        return false;
@@ -167,8 +167,7 @@ get_destination_dir(char *dest_folder)
        dir = opendir(dest_folder);
        if (dir == NULL)
        {
-               fprintf(stderr, _("%s: could not open directory \"%s\": %s\n"),
-                               progname, basedir, strerror(errno));
+               pg_log_error("could not open directory \"%s\": %m", basedir);
                exit(1);
        }
 
@@ -185,8 +184,7 @@ close_destination_dir(DIR *dest_dir, char *dest_folder)
        Assert(dest_dir != NULL && dest_folder != NULL);
        if (closedir(dest_dir))
        {
-               fprintf(stderr, _("%s: could not close directory \"%s\": %s\n"),
-                               progname, dest_folder, strerror(errno));
+               pg_log_error("could not close directory \"%s\": %m", dest_folder);
                exit(1);
        }
 }
@@ -266,16 +264,14 @@ FindStreamingStart(uint32 *tli)
                        snprintf(fullpath, sizeof(fullpath), "%s/%s", basedir, dirent->d_name);
                        if (stat(fullpath, &statbuf) != 0)
                        {
-                               fprintf(stderr, _("%s: could not stat file \"%s\": %s\n"),
-                                               progname, fullpath, strerror(errno));
+                               pg_log_error("could not stat file \"%s\": %m", fullpath);
                                exit(1);
                        }
 
                        if (statbuf.st_size != WalSegSz)
                        {
-                               fprintf(stderr,
-                                               _("%s: segment file \"%s\" has incorrect size %d, skipping\n"),
-                                               progname, dirent->d_name, (int) statbuf.st_size);
+                               pg_log_warning("segment file \"%s\" has incorrect size %d, skipping",
+                                                          dirent->d_name, (int) statbuf.st_size);
                                continue;
                        }
                }
@@ -292,25 +288,25 @@ FindStreamingStart(uint32 *tli)
                        fd = open(fullpath, O_RDONLY | PG_BINARY, 0);
                        if (fd < 0)
                        {
-                               fprintf(stderr, _("%s: could not open compressed file \"%s\": %s\n"),
-                                               progname, fullpath, strerror(errno));
+                               pg_log_error("could not open compressed file \"%s\": %m",
+                                                        fullpath);
                                exit(1);
                        }
                        if (lseek(fd, (off_t) (-4), SEEK_END) < 0)
                        {
-                               fprintf(stderr, _("%s: could not seek in compressed file \"%s\": %s\n"),
-                                               progname, fullpath, strerror(errno));
+                               pg_log_error("could not seek in compressed file \"%s\": %m",
+                                                        fullpath);
                                exit(1);
                        }
                        r = read(fd, (char *) buf, sizeof(buf));
                        if (r != sizeof(buf))
                        {
                                if (r < 0)
-                                       fprintf(stderr, _("%s: could not read compressed file \"%s\": %s\n"),
-                                                       progname, fullpath, strerror(errno));
+                                       pg_log_error("could not read compressed file \"%s\": %m",
+                                                                fullpath);
                                else
-                                       fprintf(stderr, _("%s: could not read compressed file \"%s\": read %d of %zu\n"),
-                                                       progname, fullpath, r, sizeof(buf));
+                                       pg_log_error("could not read compressed file \"%s\": read %d of %zu",
+                                                                fullpath, r, sizeof(buf));
                                exit(1);
                        }
 
@@ -320,9 +316,8 @@ FindStreamingStart(uint32 *tli)
 
                        if (bytes_out != WalSegSz)
                        {
-                               fprintf(stderr,
-                                               _("%s: compressed segment file \"%s\" has incorrect uncompressed size %d, skipping\n"),
-                                               progname, dirent->d_name, bytes_out);
+                               pg_log_warning("compressed segment file \"%s\" has incorrect uncompressed size %d, skipping",
+                                                          dirent->d_name, bytes_out);
                                continue;
                        }
                }
@@ -340,8 +335,7 @@ FindStreamingStart(uint32 *tli)
 
        if (errno)
        {
-               fprintf(stderr, _("%s: could not read directory \"%s\": %s\n"),
-                               progname, basedir, strerror(errno));
+               pg_log_error("could not read directory \"%s\": %m", basedir);
                exit(1);
        }
 
@@ -426,10 +420,9 @@ StreamLog(void)
         * Start the replication
         */
        if (verbose)
-               fprintf(stderr,
-                               _("%s: starting log streaming at %X/%X (timeline %u)\n"),
-                               progname, (uint32) (stream.startpos >> 32), (uint32) stream.startpos,
-                               stream.timeline);
+               pg_log_info("starting log streaming at %X/%X (timeline %u)",
+                                       (uint32) (stream.startpos >> 32), (uint32) stream.startpos,
+                                       stream.timeline);
 
        stream.stream_stop = stop_streaming;
        stream.stop_socket = PGINVALID_SOCKET;
@@ -446,9 +439,7 @@ StreamLog(void)
 
        if (!stream.walmethod->finish())
        {
-               fprintf(stderr,
-                               _("%s: could not finish writing WAL files: %s\n"),
-                               progname, strerror(errno));
+               pg_log_info("could not finish writing WAL files: %m");
                return;
        }
 
@@ -508,6 +499,7 @@ main(int argc, char **argv)
        uint32          hi,
                                lo;
 
+       pg_logging_init(argv[0]);
        progname = get_progname(argv[0]);
        set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_basebackup"));
 
@@ -543,8 +535,7 @@ main(int argc, char **argv)
                        case 'p':
                                if (atoi(optarg) <= 0)
                                {
-                                       fprintf(stderr, _("%s: invalid port number \"%s\"\n"),
-                                                       progname, optarg);
+                                       pg_log_error("invalid port number \"%s\"", optarg);
                                        exit(1);
                                }
                                dbport = pg_strdup(optarg);
@@ -562,8 +553,7 @@ main(int argc, char **argv)
                                standby_message_timeout = atoi(optarg) * 1000;
                                if (standby_message_timeout < 0)
                                {
-                                       fprintf(stderr, _("%s: invalid status interval \"%s\"\n"),
-                                                       progname, optarg);
+                                       pg_log_error("invalid status interval \"%s\"", optarg);
                                        exit(1);
                                }
                                break;
@@ -573,9 +563,7 @@ main(int argc, char **argv)
                        case 'E':
                                if (sscanf(optarg, "%X/%X", &hi, &lo) != 2)
                                {
-                                       fprintf(stderr,
-                                                       _("%s: could not parse end position \"%s\"\n"),
-                                                       progname, optarg);
+                                       pg_log_error("could not parse end position \"%s\"", optarg);
                                        exit(1);
                                }
                                endpos = ((uint64) hi) << 32 | lo;
@@ -590,8 +578,7 @@ main(int argc, char **argv)
                                compresslevel = atoi(optarg);
                                if (compresslevel < 0 || compresslevel > 9)
                                {
-                                       fprintf(stderr, _("%s: invalid compression level \"%s\"\n"),
-                                                       progname, optarg);
+                                       pg_log_error("invalid compression level \"%s\"", optarg);
                                        exit(1);
                                }
                                break;
@@ -627,9 +614,8 @@ main(int argc, char **argv)
         */
        if (optind < argc)
        {
-               fprintf(stderr,
-                               _("%s: too many command-line arguments (first is \"%s\")\n"),
-                               progname, argv[optind]);
+               pg_log_error("too many command-line arguments (first is \"%s\")",
+                                        argv[optind]);
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                progname);
                exit(1);
@@ -637,7 +623,7 @@ main(int argc, char **argv)
 
        if (do_drop_slot && do_create_slot)
        {
-               fprintf(stderr, _("%s: cannot use --create-slot together with --drop-slot\n"), progname);
+               pg_log_error("cannot use --create-slot together with --drop-slot");
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                progname);
                exit(1);
@@ -646,7 +632,7 @@ main(int argc, char **argv)
        if (replication_slot == NULL && (do_drop_slot || do_create_slot))
        {
                /* translator: second %s is an option name */
-               fprintf(stderr, _("%s: %s needs a slot to be specified using --slot\n"), progname,
+               pg_log_error("%s needs a slot to be specified using --slot",
                                do_drop_slot ? "--drop-slot" : "--create-slot");
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                progname);
@@ -655,7 +641,7 @@ main(int argc, char **argv)
 
        if (synchronous && !do_sync)
        {
-               fprintf(stderr, _("%s: cannot use --synchronous together with --no-sync\n"), progname);
+               pg_log_error("cannot use --synchronous together with --no-sync");
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                progname);
                exit(1);
@@ -666,7 +652,7 @@ main(int argc, char **argv)
         */
        if (basedir == NULL && !do_drop_slot && !do_create_slot)
        {
-               fprintf(stderr, _("%s: no target directory specified\n"), progname);
+               pg_log_error("no target directory specified");
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                progname);
                exit(1);
@@ -675,9 +661,7 @@ main(int argc, char **argv)
 #ifndef HAVE_LIBZ
        if (compresslevel != 0)
        {
-               fprintf(stderr,
-                               _("%s: this build does not support compression\n"),
-                               progname);
+               pg_log_error("this build does not support compression");
                exit(1);
        }
 #endif
@@ -733,9 +717,8 @@ main(int argc, char **argv)
         */
        if (db_name)
        {
-               fprintf(stderr,
-                               _("%s: replication connection using slot \"%s\" is unexpectedly database specific\n"),
-                               progname, replication_slot);
+               pg_log_error("replication connection using slot \"%s\" is unexpectedly database specific",
+                                        replication_slot);
                exit(1);
        }
 
@@ -745,9 +728,7 @@ main(int argc, char **argv)
        if (do_drop_slot)
        {
                if (verbose)
-                       fprintf(stderr,
-                                       _("%s: dropping replication slot \"%s\"\n"),
-                                       progname, replication_slot);
+                       pg_log_info("dropping replication slot \"%s\"", replication_slot);
 
                if (!DropReplicationSlot(conn, replication_slot))
                        exit(1);
@@ -758,9 +739,7 @@ main(int argc, char **argv)
        if (do_create_slot)
        {
                if (verbose)
-                       fprintf(stderr,
-                                       _("%s: creating replication slot \"%s\"\n"),
-                                       progname, replication_slot);
+                       pg_log_info("creating replication slot \"%s\"", replication_slot);
 
                if (!CreateReplicationSlot(conn, replication_slot, NULL, false, true, false,
                                                                   slot_exists_ok))
@@ -786,15 +765,14 @@ main(int argc, char **argv)
                }
                else if (noloop)
                {
-                       fprintf(stderr, _("%s: disconnected\n"), progname);
+                       pg_log_error("disconnected");
                        exit(1);
                }
                else
                {
-                       fprintf(stderr,
                        /* translator: check source for value for %d */
-                                       _("%s: disconnected; waiting %d seconds to try again\n"),
-                                       progname, RECONNECT_SLEEP_TIME);
+                       pg_log_info("disconnected; waiting %d seconds to try again",
+                                               RECONNECT_SLEEP_TIME);
                        pg_usleep(RECONNECT_SLEEP_TIME * 1000000);
                }
        }
index 10429a529d917b2e3a2b9b77dad6080e9162edb5..3c95f231a2a98201f8d8fb029a627cc010e9eba4 100644 (file)
@@ -25,6 +25,7 @@
 #include "access/xlog_internal.h"
 #include "common/file_perm.h"
 #include "common/fe_memutils.h"
+#include "fe_utils/logging.h"
 #include "getopt_long.h"
 #include "libpq-fe.h"
 #include "libpq/pqsignal.h"
@@ -131,9 +132,7 @@ sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
                return true;
 
        if (verbose)
-               fprintf(stderr,
-                               _("%s: confirming write up to %X/%X, flush to %X/%X (slot %s)\n"),
-                               progname,
+               pg_log_info("confirming write up to %X/%X, flush to %X/%X (slot %s)",
                                (uint32) (output_written_lsn >> 32), (uint32) output_written_lsn,
                                (uint32) (output_fsync_lsn >> 32), (uint32) output_fsync_lsn,
                                replication_slot);
@@ -157,8 +156,8 @@ sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
 
        if (PQputCopyData(conn, replybuf, len) <= 0 || PQflush(conn))
        {
-               fprintf(stderr, _("%s: could not send feedback packet: %s"),
-                               progname, PQerrorMessage(conn));
+               pg_log_error("could not send feedback packet: %s",
+                                        PQerrorMessage(conn));
                return false;
        }
 
@@ -193,9 +192,7 @@ OutputFsync(TimestampTz now)
 
        if (fsync(outfd) != 0)
        {
-               fprintf(stderr,
-                               _("%s: could not fsync file \"%s\": %s\n"),
-                               progname, outfile, strerror(errno));
+               pg_log_error("could not fsync file \"%s\": %m", outfile);
                return false;
        }
 
@@ -232,10 +229,9 @@ StreamLogicalLog(void)
         * Start the replication
         */
        if (verbose)
-               fprintf(stderr,
-                               _("%s: starting log streaming at %X/%X (slot %s)\n"),
-                               progname, (uint32) (startpos >> 32), (uint32) startpos,
-                               replication_slot);
+               pg_log_info("starting log streaming at %X/%X (slot %s)",
+                                       (uint32) (startpos >> 32), (uint32) startpos,
+                                       replication_slot);
 
        /* Initiate the replication stream at specified location */
        appendPQExpBuffer(query, "START_REPLICATION SLOT \"%s\" LOGICAL %X/%X",
@@ -265,8 +261,8 @@ StreamLogicalLog(void)
        res = PQexec(conn, query->data);
        if (PQresultStatus(res) != PGRES_COPY_BOTH)
        {
-               fprintf(stderr, _("%s: could not send replication command \"%s\": %s"),
-                               progname, query->data, PQresultErrorMessage(res));
+               pg_log_error("could not send replication command \"%s\": %s",
+                                        query->data, PQresultErrorMessage(res));
                PQclear(res);
                goto error;
        }
@@ -274,9 +270,7 @@ StreamLogicalLog(void)
        resetPQExpBuffer(query);
 
        if (verbose)
-               fprintf(stderr,
-                               _("%s: streaming initiated\n"),
-                               progname);
+               pg_log_info("streaming initiated");
 
        while (!time_to_abort)
        {
@@ -340,16 +334,12 @@ StreamLogicalLog(void)
                                                         S_IRUSR | S_IWUSR);
                        if (outfd == -1)
                        {
-                               fprintf(stderr,
-                                               _("%s: could not open log file \"%s\": %s\n"),
-                                               progname, outfile, strerror(errno));
+                               pg_log_error("could not open log file \"%s\": %m", outfile);
                                goto error;
                        }
 
                        if (fstat(outfd, &statbuf) != 0)
-                               fprintf(stderr,
-                                               _("%s: could not stat file \"%s\": %s\n"),
-                                               progname, outfile, strerror(errno));
+                               pg_log_error("could not stat file \"%s\": %m", outfile);
 
                        output_isfile = S_ISREG(statbuf.st_mode) && !isatty(outfd);
                }
@@ -370,9 +360,7 @@ StreamLogicalLog(void)
 
                        if (PQsocket(conn) < 0)
                        {
-                               fprintf(stderr,
-                                               _("%s: invalid socket: %s"),
-                                               progname, PQerrorMessage(conn));
+                               pg_log_error("invalid socket: %s", PQerrorMessage(conn));
                                goto error;
                        }
 
@@ -425,17 +413,15 @@ StreamLogicalLog(void)
                        }
                        else if (r < 0)
                        {
-                               fprintf(stderr, _("%s: select() failed: %s\n"),
-                                               progname, strerror(errno));
+                               pg_log_error("select() failed: %m");
                                goto error;
                        }
 
                        /* Else there is actually data on the socket */
                        if (PQconsumeInput(conn) == 0)
                        {
-                               fprintf(stderr,
-                                               _("%s: could not receive data from WAL stream: %s"),
-                                               progname, PQerrorMessage(conn));
+                               pg_log_error("could not receive data from WAL stream: %s",
+                                                        PQerrorMessage(conn));
                                goto error;
                        }
                        continue;
@@ -448,8 +434,8 @@ StreamLogicalLog(void)
                /* Failure while reading the copy stream */
                if (r == -2)
                {
-                       fprintf(stderr, _("%s: could not read COPY data: %s"),
-                                       progname, PQerrorMessage(conn));
+                       pg_log_error("could not read COPY data: %s",
+                                                PQerrorMessage(conn));
                        goto error;
                }
 
@@ -476,8 +462,7 @@ StreamLogicalLog(void)
 
                        if (r < pos + 1)
                        {
-                               fprintf(stderr, _("%s: streaming header too small: %d\n"),
-                                               progname, r);
+                               pg_log_error("streaming header too small: %d", r);
                                goto error;
                        }
                        replyRequested = copybuf[pos];
@@ -512,8 +497,8 @@ StreamLogicalLog(void)
                }
                else if (copybuf[0] != 'w')
                {
-                       fprintf(stderr, _("%s: unrecognized streaming header: \"%c\"\n"),
-                                       progname, copybuf[0]);
+                       pg_log_error("unrecognized streaming header: \"%c\"",
+                                                copybuf[0]);
                        goto error;
                }
 
@@ -528,8 +513,7 @@ StreamLogicalLog(void)
                hdr_len += 8;                   /* sendTime */
                if (r < hdr_len + 1)
                {
-                       fprintf(stderr, _("%s: streaming header too small: %d\n"),
-                                       progname, r);
+                       pg_log_error("streaming header too small: %d", r);
                        goto error;
                }
 
@@ -567,10 +551,8 @@ StreamLogicalLog(void)
 
                        if (ret < 0)
                        {
-                               fprintf(stderr,
-                                               _("%s: could not write %u bytes to log file \"%s\": %s\n"),
-                                               progname, bytes_left, outfile,
-                                               strerror(errno));
+                               pg_log_error("could not write %u bytes to log file \"%s\": %m",
+                                                        bytes_left, outfile);
                                goto error;
                        }
 
@@ -581,10 +563,8 @@ StreamLogicalLog(void)
 
                if (write(outfd, "\n", 1) != 1)
                {
-                       fprintf(stderr,
-                                       _("%s: could not write %u bytes to log file \"%s\": %s\n"),
-                                       progname, 1, outfile,
-                                       strerror(errno));
+                       pg_log_error("could not write %u bytes to log file \"%s\": %m",
+                                                1, outfile);
                        goto error;
                }
 
@@ -611,9 +591,8 @@ StreamLogicalLog(void)
        }
        else if (PQresultStatus(res) != PGRES_COMMAND_OK)
        {
-               fprintf(stderr,
-                               _("%s: unexpected termination of replication stream: %s"),
-                               progname, PQresultErrorMessage(res));
+               pg_log_error("unexpected termination of replication stream: %s",
+                                        PQresultErrorMessage(res));
                goto error;
        }
        PQclear(res);
@@ -626,8 +605,7 @@ StreamLogicalLog(void)
                OutputFsync(t);
 
                if (close(outfd) != 0)
-                       fprintf(stderr, _("%s: could not close file \"%s\": %s\n"),
-                                       progname, outfile, strerror(errno));
+                       pg_log_error("could not close file \"%s\": %m", outfile);
        }
        outfd = -1;
 error:
@@ -705,6 +683,7 @@ main(int argc, char **argv)
                                lo;
        char       *db_name;
 
+       pg_logging_init(argv[0]);
        progname = get_progname(argv[0]);
        set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_basebackup"));
 
@@ -736,8 +715,7 @@ main(int argc, char **argv)
                                fsync_interval = atoi(optarg) * 1000;
                                if (fsync_interval < 0)
                                {
-                                       fprintf(stderr, _("%s: invalid fsync interval \"%s\"\n"),
-                                                       progname, optarg);
+                                       pg_log_error("invalid fsync interval \"%s\"", optarg);
                                        exit(1);
                                }
                                break;
@@ -757,8 +735,7 @@ main(int argc, char **argv)
                        case 'p':
                                if (atoi(optarg) <= 0)
                                {
-                                       fprintf(stderr, _("%s: invalid port number \"%s\"\n"),
-                                                       progname, optarg);
+                                       pg_log_error("invalid port number \"%s\"", optarg);
                                        exit(1);
                                }
                                dbport = pg_strdup(optarg);
@@ -776,9 +753,7 @@ main(int argc, char **argv)
                        case 'I':
                                if (sscanf(optarg, "%X/%X", &hi, &lo) != 2)
                                {
-                                       fprintf(stderr,
-                                                       _("%s: could not parse start position \"%s\"\n"),
-                                                       progname, optarg);
+                                       pg_log_error("could not parse start position \"%s\"", optarg);
                                        exit(1);
                                }
                                startpos = ((uint64) hi) << 32 | lo;
@@ -786,9 +761,7 @@ main(int argc, char **argv)
                        case 'E':
                                if (sscanf(optarg, "%X/%X", &hi, &lo) != 2)
                                {
-                                       fprintf(stderr,
-                                                       _("%s: could not parse end position \"%s\"\n"),
-                                                       progname, optarg);
+                                       pg_log_error("could not parse end position \"%s\"", optarg);
                                        exit(1);
                                }
                                endpos = ((uint64) hi) << 32 | lo;
@@ -820,8 +793,7 @@ main(int argc, char **argv)
                                standby_message_timeout = atoi(optarg) * 1000;
                                if (standby_message_timeout < 0)
                                {
-                                       fprintf(stderr, _("%s: invalid status interval \"%s\"\n"),
-                                                       progname, optarg);
+                                       pg_log_error("invalid status interval \"%s\"", optarg);
                                        exit(1);
                                }
                                break;
@@ -858,9 +830,8 @@ main(int argc, char **argv)
         */
        if (optind < argc)
        {
-               fprintf(stderr,
-                               _("%s: too many command-line arguments (first is \"%s\")\n"),
-                               progname, argv[optind]);
+               pg_log_error("too many command-line arguments (first is \"%s\")",
+                                        argv[optind]);
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                progname);
                exit(1);
@@ -871,7 +842,7 @@ main(int argc, char **argv)
         */
        if (replication_slot == NULL)
        {
-               fprintf(stderr, _("%s: no slot specified\n"), progname);
+               pg_log_error("no slot specified");
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                progname);
                exit(1);
@@ -879,7 +850,7 @@ main(int argc, char **argv)
 
        if (do_start_slot && outfile == NULL)
        {
-               fprintf(stderr, _("%s: no target file specified\n"), progname);
+               pg_log_error("no target file specified");
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                progname);
                exit(1);
@@ -887,7 +858,7 @@ main(int argc, char **argv)
 
        if (!do_drop_slot && dbname == NULL)
        {
-               fprintf(stderr, _("%s: no database specified\n"), progname);
+               pg_log_error("no database specified");
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                progname);
                exit(1);
@@ -895,7 +866,7 @@ main(int argc, char **argv)
 
        if (!do_drop_slot && !do_create_slot && !do_start_slot)
        {
-               fprintf(stderr, _("%s: at least one action needs to be specified\n"), progname);
+               pg_log_error("at least one action needs to be specified");
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                progname);
                exit(1);
@@ -903,7 +874,7 @@ main(int argc, char **argv)
 
        if (do_drop_slot && (do_create_slot || do_start_slot))
        {
-               fprintf(stderr, _("%s: cannot use --create-slot or --start together with --drop-slot\n"), progname);
+               pg_log_error("cannot use --create-slot or --start together with --drop-slot");
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                progname);
                exit(1);
@@ -911,7 +882,7 @@ main(int argc, char **argv)
 
        if (startpos != InvalidXLogRecPtr && (do_create_slot || do_drop_slot))
        {
-               fprintf(stderr, _("%s: cannot use --create-slot or --drop-slot together with --startpos\n"), progname);
+               pg_log_error("cannot use --create-slot or --drop-slot together with --startpos");
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                progname);
                exit(1);
@@ -919,9 +890,7 @@ main(int argc, char **argv)
 
        if (endpos != InvalidXLogRecPtr && !do_start_slot)
        {
-               fprintf(stderr,
-                               _("%s: --endpos may only be specified with --start\n"),
-                               progname);
+               pg_log_error("--endpos may only be specified with --start");
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                progname);
                exit(1);
@@ -952,9 +921,7 @@ main(int argc, char **argv)
 
        if (db_name == NULL)
        {
-               fprintf(stderr,
-                               _("%s: could not establish database-specific replication connection\n"),
-                               progname);
+               pg_log_error("could not establish database-specific replication connection");
                exit(1);
        }
 
@@ -972,9 +939,7 @@ main(int argc, char **argv)
        if (do_drop_slot)
        {
                if (verbose)
-                       fprintf(stderr,
-                                       _("%s: dropping replication slot \"%s\"\n"),
-                                       progname, replication_slot);
+                       pg_log_info("dropping replication slot \"%s\"", replication_slot);
 
                if (!DropReplicationSlot(conn, replication_slot))
                        exit(1);
@@ -984,9 +949,7 @@ main(int argc, char **argv)
        if (do_create_slot)
        {
                if (verbose)
-                       fprintf(stderr,
-                                       _("%s: creating replication slot \"%s\"\n"),
-                                       progname, replication_slot);
+                       pg_log_info("creating replication slot \"%s\"", replication_slot);
 
                if (!CreateReplicationSlot(conn, replication_slot, plugin, false,
                                                                   false, false, slot_exists_ok))
@@ -1011,15 +974,14 @@ main(int argc, char **argv)
                }
                else if (noloop)
                {
-                       fprintf(stderr, _("%s: disconnected\n"), progname);
+                       pg_log_error("disconnected");
                        exit(1);
                }
                else
                {
-                       fprintf(stderr,
                        /* translator: check source for value for %d */
-                                       _("%s: disconnected; waiting %d seconds to try again\n"),
-                                       progname, RECONNECT_SLEEP_TIME);
+                       pg_log_info("disconnected; waiting %d seconds to try again",
+                                               RECONNECT_SLEEP_TIME);
                        pg_usleep(RECONNECT_SLEEP_TIME * 1000000);
                }
        }
@@ -1058,12 +1020,11 @@ prepareToTerminate(PGconn *conn, XLogRecPtr endpos, bool keepalive, XLogRecPtr l
        if (verbose)
        {
                if (keepalive)
-                       fprintf(stderr, "%s: endpos %X/%X reached by keepalive\n",
-                                       progname,
+                       pg_log_info("endpos %X/%X reached by keepalive",
                                        (uint32) (endpos >> 32), (uint32) endpos);
                else
-                       fprintf(stderr, "%s: endpos %X/%X reached by record at %X/%X\n",
-                                       progname, (uint32) (endpos >> 32), (uint32) (endpos),
+                       pg_log_info("endpos %X/%X reached by record at %X/%X",
+                                       (uint32) (endpos >> 32), (uint32) (endpos),
                                        (uint32) (lsn >> 32), (uint32) lsn);
 
        }
index 692d13716e4c0c4897ba33d0519ae34a4cb906ad..0ff9aa19a9e8dd6a04538181f82a99fea97437f3 100644 (file)
@@ -27,6 +27,7 @@
 #include "libpq-fe.h"
 #include "access/xlog_internal.h"
 #include "common/file_utils.h"
+#include "fe_utils/logging.h"
 
 
 /* fd and filename for currently open WAL file */
@@ -68,8 +69,8 @@ mark_file_as_archived(StreamCtl *stream, const char *fname)
        f = stream->walmethod->open_for_write(tmppath, NULL, 0);
        if (f == NULL)
        {
-               fprintf(stderr, _("%s: could not create archive status file \"%s\": %s\n"),
-                               progname, tmppath, stream->walmethod->getlasterror());
+               pg_log_error("could not create archive status file \"%s\": %s",
+                                        tmppath, stream->walmethod->getlasterror());
                return false;
        }
 
@@ -115,9 +116,8 @@ open_walfile(StreamCtl *stream, XLogRecPtr startpoint)
                size = stream->walmethod->get_file_size(fn);
                if (size < 0)
                {
-                       fprintf(stderr,
-                                       _("%s: could not get size of write-ahead log file \"%s\": %s\n"),
-                                       progname, fn, stream->walmethod->getlasterror());
+                       pg_log_error("could not get size of write-ahead log file \"%s\": %s",
+                                                fn, stream->walmethod->getlasterror());
                        return false;
                }
                if (size == WalSegSz)
@@ -126,18 +126,16 @@ open_walfile(StreamCtl *stream, XLogRecPtr startpoint)
                        f = stream->walmethod->open_for_write(current_walfile_name, stream->partial_suffix, 0);
                        if (f == NULL)
                        {
-                               fprintf(stderr,
-                                               _("%s: could not open existing write-ahead log file \"%s\": %s\n"),
-                                               progname, fn, stream->walmethod->getlasterror());
+                               pg_log_error("could not open existing write-ahead log file \"%s\": %s",
+                                                        fn, stream->walmethod->getlasterror());
                                return false;
                        }
 
                        /* fsync file in case of a previous crash */
                        if (stream->walmethod->sync(f) != 0)
                        {
-                               fprintf(stderr,
-                                               _("%s: could not fsync existing write-ahead log file \"%s\": %s\n"),
-                                               progname, fn, stream->walmethod->getlasterror());
+                               pg_log_error("could not fsync existing write-ahead log file \"%s\": %s",
+                                                        fn, stream->walmethod->getlasterror());
                                stream->walmethod->close(f, CLOSE_UNLINK);
                                return false;
                        }
@@ -150,11 +148,10 @@ open_walfile(StreamCtl *stream, XLogRecPtr startpoint)
                        /* if write didn't set errno, assume problem is no disk space */
                        if (errno == 0)
                                errno = ENOSPC;
-                       fprintf(stderr,
-                                       ngettext("%s: write-ahead log file \"%s\" has %d byte, should be 0 or %d\n",
-                                                        "%s: write-ahead log file \"%s\" has %d bytes, should be 0 or %d\n",
-                                                        size),
-                                       progname, fn, (int) size, WalSegSz);
+                       pg_log_error(ngettext("write-ahead log file \"%s\" has %d byte, should be 0 or %d",
+                                                                 "write-ahead log file \"%s\" has %d bytes, should be 0 or %d",
+                                                                 size),
+                                                fn, (int) size, WalSegSz);
                        return false;
                }
                /* File existed and was empty, so fall through and open */
@@ -166,9 +163,8 @@ open_walfile(StreamCtl *stream, XLogRecPtr startpoint)
                                                                                  stream->partial_suffix, WalSegSz);
        if (f == NULL)
        {
-               fprintf(stderr,
-                               _("%s: could not open write-ahead log file \"%s\": %s\n"),
-                               progname, fn, stream->walmethod->getlasterror());
+               pg_log_error("could not open write-ahead log file \"%s\": %s",
+                                        fn, stream->walmethod->getlasterror());
                return false;
        }
 
@@ -193,9 +189,8 @@ close_walfile(StreamCtl *stream, XLogRecPtr pos)
        currpos = stream->walmethod->get_current_pos(walfile);
        if (currpos == -1)
        {
-               fprintf(stderr,
-                               _("%s: could not determine seek position in file \"%s\": %s\n"),
-                               progname, current_walfile_name, stream->walmethod->getlasterror());
+               pg_log_error("could not determine seek position in file \"%s\": %s",
+                                        current_walfile_name, stream->walmethod->getlasterror());
                stream->walmethod->close(walfile, CLOSE_UNLINK);
                walfile = NULL;
 
@@ -208,9 +203,8 @@ close_walfile(StreamCtl *stream, XLogRecPtr pos)
                        r = stream->walmethod->close(walfile, CLOSE_NORMAL);
                else
                {
-                       fprintf(stderr,
-                                       _("%s: not renaming \"%s%s\", segment is not complete\n"),
-                                       progname, current_walfile_name, stream->partial_suffix);
+                       pg_log_info("not renaming \"%s%s\", segment is not complete",
+                                               current_walfile_name, stream->partial_suffix);
                        r = stream->walmethod->close(walfile, CLOSE_NO_RENAME);
                }
        }
@@ -221,8 +215,8 @@ close_walfile(StreamCtl *stream, XLogRecPtr pos)
 
        if (r != 0)
        {
-               fprintf(stderr, _("%s: could not close file \"%s\": %s\n"),
-                               progname, current_walfile_name, stream->walmethod->getlasterror());
+               pg_log_error("could not close file \"%s\": %s",
+                                        current_walfile_name, stream->walmethod->getlasterror());
                return false;
        }
 
@@ -278,23 +272,23 @@ writeTimeLineHistoryFile(StreamCtl *stream, char *filename, char *content)
        TLHistoryFileName(histfname, stream->timeline);
        if (strcmp(histfname, filename) != 0)
        {
-               fprintf(stderr, _("%s: server reported unexpected history file name for timeline %u: %s\n"),
-                               progname, stream->timeline, filename);
+               pg_log_error("server reported unexpected history file name for timeline %u: %s",
+                                        stream->timeline, filename);
                return false;
        }
 
        f = stream->walmethod->open_for_write(histfname, ".tmp", 0);
        if (f == NULL)
        {
-               fprintf(stderr, _("%s: could not create timeline history file \"%s\": %s\n"),
-                               progname, histfname, stream->walmethod->getlasterror());
+               pg_log_error("could not create timeline history file \"%s\": %s",
+                                        histfname, stream->walmethod->getlasterror());
                return false;
        }
 
        if ((int) stream->walmethod->write(f, content, size) != size)
        {
-               fprintf(stderr, _("%s: could not write timeline history file \"%s\": %s\n"),
-                               progname, histfname, stream->walmethod->getlasterror());
+               pg_log_error("could not write timeline history file \"%s\": %s",
+                                        histfname, stream->walmethod->getlasterror());
 
                /*
                 * If we fail to make the file, delete it to release disk space
@@ -306,8 +300,8 @@ writeTimeLineHistoryFile(StreamCtl *stream, char *filename, char *content)
 
        if (stream->walmethod->close(f, CLOSE_NORMAL) != 0)
        {
-               fprintf(stderr, _("%s: could not close file \"%s\": %s\n"),
-                               progname, histfname, stream->walmethod->getlasterror());
+               pg_log_error("could not close file \"%s\": %s",
+                                        histfname, stream->walmethod->getlasterror());
                return false;
        }
 
@@ -349,8 +343,8 @@ sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyReque
 
        if (PQputCopyData(conn, replybuf, len) <= 0 || PQflush(conn))
        {
-               fprintf(stderr, _("%s: could not send feedback packet: %s"),
-                               progname, PQerrorMessage(conn));
+               pg_log_error("could not send feedback packet: %s",
+                                        PQerrorMessage(conn));
                return false;
        }
 
@@ -383,8 +377,7 @@ CheckServerVersionForStreaming(PGconn *conn)
        {
                const char *serverver = PQparameterStatus(conn, "server_version");
 
-               fprintf(stderr, _("%s: incompatible server version %s; client does not support streaming from server versions older than %s\n"),
-                               progname,
+               pg_log_error("incompatible server version %s; client does not support streaming from server versions older than %s",
                                serverver ? serverver : "'unknown'",
                                "9.3");
                return false;
@@ -393,8 +386,7 @@ CheckServerVersionForStreaming(PGconn *conn)
        {
                const char *serverver = PQparameterStatus(conn, "server_version");
 
-               fprintf(stderr, _("%s: incompatible server version %s; client does not support streaming from server versions newer than %s\n"),
-                               progname,
+               pg_log_error("incompatible server version %s; client does not support streaming from server versions newer than %s",
                                serverver ? serverver : "'unknown'",
                                PG_VERSION);
                return false;
@@ -489,33 +481,28 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
                res = PQexec(conn, "IDENTIFY_SYSTEM");
                if (PQresultStatus(res) != PGRES_TUPLES_OK)
                {
-                       fprintf(stderr,
-                                       _("%s: could not send replication command \"%s\": %s"),
-                                       progname, "IDENTIFY_SYSTEM", PQerrorMessage(conn));
+                       pg_log_error("could not send replication command \"%s\": %s",
+                                                "IDENTIFY_SYSTEM", PQerrorMessage(conn));
                        PQclear(res);
                        return false;
                }
                if (PQntuples(res) != 1 || PQnfields(res) < 3)
                {
-                       fprintf(stderr,
-                                       _("%s: could not identify system: got %d rows and %d fields, expected %d rows and %d or more fields\n"),
-                                       progname, PQntuples(res), PQnfields(res), 1, 3);
+                       pg_log_error("could not identify system: got %d rows and %d fields, expected %d rows and %d or more fields",
+                                                PQntuples(res), PQnfields(res), 1, 3);
                        PQclear(res);
                        return false;
                }
                if (strcmp(stream->sysidentifier, PQgetvalue(res, 0, 0)) != 0)
                {
-                       fprintf(stderr,
-                                       _("%s: system identifier does not match between base backup and streaming connection\n"),
-                                       progname);
+                       pg_log_error("system identifier does not match between base backup and streaming connection");
                        PQclear(res);
                        return false;
                }
                if (stream->timeline > atoi(PQgetvalue(res, 0, 1)))
                {
-                       fprintf(stderr,
-                                       _("%s: starting timeline %u is not present in the server\n"),
-                                       progname, stream->timeline);
+                       pg_log_error("starting timeline %u is not present in the server",
+                                                stream->timeline);
                        PQclear(res);
                        return false;
                }
@@ -543,8 +530,8 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
                        if (PQresultStatus(res) != PGRES_TUPLES_OK)
                        {
                                /* FIXME: we might send it ok, but get an error */
-                               fprintf(stderr, _("%s: could not send replication command \"%s\": %s"),
-                                               progname, "TIMELINE_HISTORY", PQresultErrorMessage(res));
+                               pg_log_error("could not send replication command \"%s\": %s",
+                                                        "TIMELINE_HISTORY", PQresultErrorMessage(res));
                                PQclear(res);
                                return false;
                        }
@@ -555,9 +542,8 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
                         */
                        if (PQnfields(res) != 2 || PQntuples(res) != 1)
                        {
-                               fprintf(stderr,
-                                               _("%s: unexpected response to TIMELINE_HISTORY command: got %d rows and %d fields, expected %d rows and %d fields\n"),
-                                               progname, PQntuples(res), PQnfields(res), 1, 2);
+                               pg_log_warning("unexpected response to TIMELINE_HISTORY command: got %d rows and %d fields, expected %d rows and %d fields",
+                                                          PQntuples(res), PQnfields(res), 1, 2);
                        }
 
                        /* Write the history file to disk */
@@ -583,8 +569,8 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
                res = PQexec(conn, query);
                if (PQresultStatus(res) != PGRES_COPY_BOTH)
                {
-                       fprintf(stderr, _("%s: could not send replication command \"%s\": %s"),
-                                       progname, "START_REPLICATION", PQresultErrorMessage(res));
+                       pg_log_error("could not send replication command \"%s\": %s",
+                                                "START_REPLICATION", PQresultErrorMessage(res));
                        PQclear(res);
                        return false;
                }
@@ -627,16 +613,13 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
                        /* Sanity check the values the server gave us */
                        if (newtimeline <= stream->timeline)
                        {
-                               fprintf(stderr,
-                                               _("%s: server reported unexpected next timeline %u, following timeline %u\n"),
-                                               progname, newtimeline, stream->timeline);
+                               pg_log_error("server reported unexpected next timeline %u, following timeline %u",
+                                                        newtimeline, stream->timeline);
                                goto error;
                        }
                        if (stream->startpos > stoppos)
                        {
-                               fprintf(stderr,
-                                               _("%s: server stopped streaming timeline %u at %X/%X, but reported next timeline %u to begin at %X/%X\n"),
-                                               progname,
+                               pg_log_error("server stopped streaming timeline %u at %X/%X, but reported next timeline %u to begin at %X/%X",
                                                stream->timeline, (uint32) (stoppos >> 32), (uint32) stoppos,
                                                newtimeline, (uint32) (stream->startpos >> 32), (uint32) stream->startpos);
                                goto error;
@@ -646,9 +629,8 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
                        res = PQgetResult(conn);
                        if (PQresultStatus(res) != PGRES_COMMAND_OK)
                        {
-                               fprintf(stderr,
-                                               _("%s: unexpected termination of replication stream: %s"),
-                                               progname, PQresultErrorMessage(res));
+                               pg_log_error("unexpected termination of replication stream: %s",
+                                                        PQresultErrorMessage(res));
                                PQclear(res);
                                goto error;
                        }
@@ -677,17 +659,15 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
                                return true;
                        else
                        {
-                               fprintf(stderr, _("%s: replication stream was terminated before stop point\n"),
-                                               progname);
+                               pg_log_error("replication stream was terminated before stop point");
                                goto error;
                        }
                }
                else
                {
                        /* Server returned an error. */
-                       fprintf(stderr,
-                                       _("%s: unexpected termination of replication stream: %s"),
-                                       progname, PQresultErrorMessage(res));
+                       pg_log_error("unexpected termination of replication stream: %s",
+                                                PQresultErrorMessage(res));
                        PQclear(res);
                        goto error;
                }
@@ -695,8 +675,8 @@ ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
 
 error:
        if (walfile != NULL && stream->walmethod->close(walfile, CLOSE_NO_RENAME) != 0)
-               fprintf(stderr, _("%s: could not close file \"%s\": %s\n"),
-                               progname, current_walfile_name, stream->walmethod->getlasterror());
+               pg_log_error("could not close file \"%s\": %s",
+                                        current_walfile_name, stream->walmethod->getlasterror());
        walfile = NULL;
        return false;
 }
@@ -725,9 +705,8 @@ ReadEndOfStreamingResult(PGresult *res, XLogRecPtr *startpos, uint32 *timeline)
         */
        if (PQnfields(res) < 2 || PQntuples(res) != 1)
        {
-               fprintf(stderr,
-                               _("%s: unexpected result set after end-of-timeline: got %d rows and %d fields, expected %d rows and %d fields\n"),
-                               progname, PQntuples(res), PQnfields(res), 1, 2);
+               pg_log_error("unexpected result set after end-of-timeline: got %d rows and %d fields, expected %d rows and %d fields",
+                                        PQntuples(res), PQnfields(res), 1, 2);
                return false;
        }
 
@@ -735,9 +714,8 @@ ReadEndOfStreamingResult(PGresult *res, XLogRecPtr *startpos, uint32 *timeline)
        if (sscanf(PQgetvalue(res, 0, 1), "%X/%X", &startpos_xlogid,
                           &startpos_xrecoff) != 2)
        {
-               fprintf(stderr,
-                               _("%s: could not parse next timeline's starting point \"%s\"\n"),
-                               progname, PQgetvalue(res, 0, 1));
+               pg_log_error("could not parse next timeline's starting point \"%s\"",
+                                        PQgetvalue(res, 0, 1));
                return false;
        }
        *startpos = ((uint64) startpos_xlogid << 32) | startpos_xrecoff;
@@ -785,8 +763,8 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
                {
                        if (stream->walmethod->sync(walfile) != 0)
                        {
-                               fprintf(stderr, _("%s: could not fsync file \"%s\": %s\n"),
-                                               progname, current_walfile_name, stream->walmethod->getlasterror());
+                               pg_log_error("could not fsync file \"%s\": %s",
+                                                        current_walfile_name, stream->walmethod->getlasterror());
                                goto error;
                        }
                        lastFlushPosition = blockpos;
@@ -855,8 +833,8 @@ HandleCopyStream(PGconn *conn, StreamCtl *stream,
                        }
                        else
                        {
-                               fprintf(stderr, _("%s: unrecognized streaming header: \"%c\"\n"),
-                                               progname, copybuf[0]);
+                               pg_log_error("unrecognized streaming header: \"%c\"",
+                                                        copybuf[0]);
                                goto error;
                        }
 
@@ -895,8 +873,7 @@ CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
        connsocket = PQsocket(conn);
        if (connsocket < 0)
        {
-               fprintf(stderr, _("%s: invalid socket: %s"), progname,
-                               PQerrorMessage(conn));
+               pg_log_error("invalid socket: %s", PQerrorMessage(conn));
                return -1;
        }
 
@@ -924,8 +901,7 @@ CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
        {
                if (errno == EINTR)
                        return 0;                       /* Got a signal, so not an error */
-               fprintf(stderr, _("%s: select() failed: %s\n"),
-                               progname, strerror(errno));
+               pg_log_error("select() failed: %m");
                return -1;
        }
        if (ret > 0 && FD_ISSET(connsocket, &input_mask))
@@ -975,9 +951,8 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
                /* Now there is actually data on the socket */
                if (PQconsumeInput(conn) == 0)
                {
-                       fprintf(stderr,
-                                       _("%s: could not receive data from WAL stream: %s"),
-                                       progname, PQerrorMessage(conn));
+                       pg_log_error("could not receive data from WAL stream: %s",
+                                                PQerrorMessage(conn));
                        return -1;
                }
 
@@ -990,8 +965,7 @@ CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
                return -2;
        if (rawlen == -2)
        {
-               fprintf(stderr, _("%s: could not read COPY data: %s"),
-                               progname, PQerrorMessage(conn));
+               pg_log_error("could not read COPY data: %s", PQerrorMessage(conn));
                return -1;
        }
 
@@ -1021,8 +995,7 @@ ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
 
        if (len < pos + 1)
        {
-               fprintf(stderr, _("%s: streaming header too small: %d\n"),
-                               progname, len);
+               pg_log_error("streaming header too small: %d", len);
                return false;
        }
        replyRequested = copybuf[pos];
@@ -1042,8 +1015,8 @@ ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
                         */
                        if (stream->walmethod->sync(walfile) != 0)
                        {
-                               fprintf(stderr, _("%s: could not fsync file \"%s\": %s\n"),
-                                               progname, current_walfile_name, stream->walmethod->getlasterror());
+                               pg_log_error("could not fsync file \"%s\": %s",
+                                                        current_walfile_name, stream->walmethod->getlasterror());
                                return false;
                        }
                        lastFlushPosition = blockpos;
@@ -1088,8 +1061,7 @@ ProcessXLogDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
        hdr_len += 8;                           /* sendTime */
        if (len < hdr_len)
        {
-               fprintf(stderr, _("%s: streaming header too small: %d\n"),
-                               progname, len);
+               pg_log_error("streaming header too small: %d", len);
                return false;
        }
        *blockpos = fe_recvint64(&copybuf[1]);
@@ -1106,9 +1078,8 @@ ProcessXLogDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
                /* No file open yet */
                if (xlogoff != 0)
                {
-                       fprintf(stderr,
-                                       _("%s: received write-ahead log record for offset %u with no file open\n"),
-                                       progname, xlogoff);
+                       pg_log_error("received write-ahead log record for offset %u with no file open",
+                                                xlogoff);
                        return false;
                }
        }
@@ -1117,9 +1088,8 @@ ProcessXLogDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
                /* More data in existing segment */
                if (stream->walmethod->get_current_pos(walfile) != xlogoff)
                {
-                       fprintf(stderr,
-                                       _("%s: got WAL data offset %08x, expected %08x\n"),
-                                       progname, xlogoff, (int) stream->walmethod->get_current_pos(walfile));
+                       pg_log_error("got WAL data offset %08x, expected %08x",
+                                                xlogoff, (int) stream->walmethod->get_current_pos(walfile));
                        return false;
                }
        }
@@ -1152,10 +1122,9 @@ ProcessXLogDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
                if (stream->walmethod->write(walfile, copybuf + hdr_len + bytes_written,
                                                                         bytes_to_write) != bytes_to_write)
                {
-                       fprintf(stderr,
-                                       _("%s: could not write %u bytes to WAL file \"%s\": %s\n"),
-                                       progname, bytes_to_write, current_walfile_name,
-                                       stream->walmethod->getlasterror());
+                       pg_log_error("could not write %u bytes to WAL file \"%s\": %s",
+                                                bytes_to_write, current_walfile_name,
+                                                stream->walmethod->getlasterror());
                        return false;
                }
 
@@ -1178,8 +1147,8 @@ ProcessXLogDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
                        {
                                if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
                                {
-                                       fprintf(stderr, _("%s: could not send copy-end packet: %s"),
-                                                       progname, PQerrorMessage(conn));
+                                       pg_log_error("could not send copy-end packet: %s",
+                                                                PQerrorMessage(conn));
                                        return false;
                                }
                                still_sending = false;
@@ -1218,9 +1187,8 @@ HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
                {
                        if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
                        {
-                               fprintf(stderr,
-                                               _("%s: could not send copy-end packet: %s"),
-                                               progname, PQerrorMessage(conn));
+                               pg_log_error("could not send copy-end packet: %s",
+                                                        PQerrorMessage(conn));
                                PQclear(res);
                                return NULL;
                        }
@@ -1250,8 +1218,8 @@ CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos,
                }
                if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
                {
-                       fprintf(stderr, _("%s: could not send copy-end packet: %s"),
-                                       progname, PQerrorMessage(conn));
+                       pg_log_error("could not send copy-end packet: %s",
+                                                PQerrorMessage(conn));
                        return false;
                }
                still_sending = false;
index 7e86830ad8857c655b3ccba2be8eddf3089465c1..ab2e55d69508a246405b115934fca883dd22de47 100644 (file)
@@ -26,6 +26,7 @@
 #include "common/file_perm.h"
 #include "datatype/timestamp.h"
 #include "fe_utils/connect.h"
+#include "fe_utils/logging.h"
 #include "port/pg_bswap.h"
 #include "pqexpbuffer.h"
 
@@ -90,7 +91,7 @@ GetConnection(void)
                conn_opts = PQconninfoParse(connection_string, &err_msg);
                if (conn_opts == NULL)
                {
-                       fprintf(stderr, "%s: %s", progname, err_msg);
+                       pg_log_error("%s", err_msg);
                        exit(1);
                }
 
@@ -183,8 +184,7 @@ GetConnection(void)
                 */
                if (!tmpconn)
                {
-                       fprintf(stderr, _("%s: could not connect to server\n"),
-                                       progname);
+                       pg_log_error("could not connect to server");
                        exit(1);
                }
 
@@ -201,8 +201,8 @@ GetConnection(void)
 
        if (PQstatus(tmpconn) != CONNECTION_OK)
        {
-               fprintf(stderr, _("%s: could not connect to server: %s"),
-                               progname, PQerrorMessage(tmpconn));
+               pg_log_error("could not connect to server: %s",
+                                        PQerrorMessage(tmpconn));
                PQfinish(tmpconn);
                free(values);
                free(keywords);
@@ -230,8 +230,8 @@ GetConnection(void)
                res = PQexec(tmpconn, ALWAYS_SECURE_SEARCH_PATH_SQL);
                if (PQresultStatus(res) != PGRES_TUPLES_OK)
                {
-                       fprintf(stderr, _("%s: could not clear search_path: %s"),
-                                       progname, PQerrorMessage(tmpconn));
+                       pg_log_error("could not clear search_path: %s",
+                                                PQerrorMessage(tmpconn));
                        PQclear(res);
                        PQfinish(tmpconn);
                        exit(1);
@@ -246,18 +246,14 @@ GetConnection(void)
        tmpparam = PQparameterStatus(tmpconn, "integer_datetimes");
        if (!tmpparam)
        {
-               fprintf(stderr,
-                               _("%s: could not determine server setting for integer_datetimes\n"),
-                               progname);
+               pg_log_error("could not determine server setting for integer_datetimes");
                PQfinish(tmpconn);
                exit(1);
        }
 
        if (strcmp(tmpparam, "on") != 0)
        {
-               fprintf(stderr,
-                               _("%s: integer_datetimes compile flag does not match server\n"),
-                               progname);
+               pg_log_error("integer_datetimes compile flag does not match server");
                PQfinish(tmpconn);
                exit(1);
        }
@@ -300,17 +296,16 @@ RetrieveWalSegSize(PGconn *conn)
        res = PQexec(conn, "SHOW wal_segment_size");
        if (PQresultStatus(res) != PGRES_TUPLES_OK)
        {
-               fprintf(stderr, _("%s: could not send replication command \"%s\": %s"),
-                               progname, "SHOW wal_segment_size", PQerrorMessage(conn));
+               pg_log_error("could not send replication command \"%s\": %s",
+                                        "SHOW wal_segment_size", PQerrorMessage(conn));
 
                PQclear(res);
                return false;
        }
        if (PQntuples(res) != 1 || PQnfields(res) < 1)
        {
-               fprintf(stderr,
-                               _("%s: could not fetch WAL segment size: got %d rows and %d fields, expected %d rows and %d or more fields\n"),
-                               progname, PQntuples(res), PQnfields(res), 1, 1);
+               pg_log_error("could not fetch WAL segment size: got %d rows and %d fields, expected %d rows and %d or more fields",
+                                        PQntuples(res), PQnfields(res), 1, 1);
 
                PQclear(res);
                return false;
@@ -319,8 +314,7 @@ RetrieveWalSegSize(PGconn *conn)
        /* fetch xlog value and unit from the result */
        if (sscanf(PQgetvalue(res, 0, 0), "%d%s", &xlog_val, xlog_unit) != 2)
        {
-               fprintf(stderr, _("%s: WAL segment size could not be parsed\n"),
-                               progname);
+               pg_log_error("WAL segment size could not be parsed");
                return false;
        }
 
@@ -335,11 +329,10 @@ RetrieveWalSegSize(PGconn *conn)
 
        if (!IsValidWalSegSize(WalSegSz))
        {
-               fprintf(stderr,
-                               ngettext("%s: WAL segment size must be a power of two between 1 MB and 1 GB, but the remote server reported a value of %d byte\n",
-                                                "%s: WAL segment size must be a power of two between 1 MB and 1 GB, but the remote server reported a value of %d bytes\n",
-                                                WalSegSz),
-                               progname, WalSegSz);
+               pg_log_error(ngettext("WAL segment size must be a power of two between 1 MB and 1 GB, but the remote server reported a value of %d byte",
+                                                         "WAL segment size must be a power of two between 1 MB and 1 GB, but the remote server reported a value of %d bytes",
+                                                         WalSegSz),
+                                        WalSegSz);
                return false;
        }
 
@@ -374,17 +367,16 @@ RetrieveDataDirCreatePerm(PGconn *conn)
        res = PQexec(conn, "SHOW data_directory_mode");
        if (PQresultStatus(res) != PGRES_TUPLES_OK)
        {
-               fprintf(stderr, _("%s: could not send replication command \"%s\": %s"),
-                               progname, "SHOW data_directory_mode", PQerrorMessage(conn));
+               pg_log_error("could not send replication command \"%s\": %s",
+                                        "SHOW data_directory_mode", PQerrorMessage(conn));
 
                PQclear(res);
                return false;
        }
        if (PQntuples(res) != 1 || PQnfields(res) < 1)
        {
-               fprintf(stderr,
-                               _("%s: could not fetch group access flag: got %d rows and %d fields, expected %d rows and %d or more fields\n"),
-                               progname, PQntuples(res), PQnfields(res), 1, 1);
+               pg_log_error("could not fetch group access flag: got %d rows and %d fields, expected %d rows and %d or more fields",
+                                        PQntuples(res), PQnfields(res), 1, 1);
 
                PQclear(res);
                return false;
@@ -392,8 +384,8 @@ RetrieveDataDirCreatePerm(PGconn *conn)
 
        if (sscanf(PQgetvalue(res, 0, 0), "%o", &data_directory_mode) != 1)
        {
-               fprintf(stderr, _("%s: group access flag could not be parsed: %s\n"),
-                               progname, PQgetvalue(res, 0, 0));
+               pg_log_error("group access flag could not be parsed: %s",
+                                        PQgetvalue(res, 0, 0));
 
                PQclear(res);
                return false;
@@ -427,17 +419,16 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
        res = PQexec(conn, "IDENTIFY_SYSTEM");
        if (PQresultStatus(res) != PGRES_TUPLES_OK)
        {
-               fprintf(stderr, _("%s: could not send replication command \"%s\": %s"),
-                               progname, "IDENTIFY_SYSTEM", PQerrorMessage(conn));
+               pg_log_error("could not send replication command \"%s\": %s",
+                                        "IDENTIFY_SYSTEM", PQerrorMessage(conn));
 
                PQclear(res);
                return false;
        }
        if (PQntuples(res) != 1 || PQnfields(res) < 3)
        {
-               fprintf(stderr,
-                               _("%s: could not identify system: got %d rows and %d fields, expected %d rows and %d or more fields\n"),
-                               progname, PQntuples(res), PQnfields(res), 1, 3);
+               pg_log_error("could not identify system: got %d rows and %d fields, expected %d rows and %d or more fields",
+                                        PQntuples(res), PQnfields(res), 1, 3);
 
                PQclear(res);
                return false;
@@ -456,9 +447,8 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
        {
                if (sscanf(PQgetvalue(res, 0, 2), "%X/%X", &hi, &lo) != 2)
                {
-                       fprintf(stderr,
-                                       _("%s: could not parse write-ahead log location \"%s\"\n"),
-                                       progname, PQgetvalue(res, 0, 2));
+                       pg_log_error("could not parse write-ahead log location \"%s\"",
+                                                PQgetvalue(res, 0, 2));
 
                        PQclear(res);
                        return false;
@@ -474,9 +464,8 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
                {
                        if (PQnfields(res) < 4)
                        {
-                               fprintf(stderr,
-                                               _("%s: could not identify system: got %d rows and %d fields, expected %d rows and %d or more fields\n"),
-                                               progname, PQntuples(res), PQnfields(res), 1, 4);
+                               pg_log_error("could not identify system: got %d rows and %d fields, expected %d rows and %d or more fields",
+                                                        PQntuples(res), PQnfields(res), 1, 4);
 
                                PQclear(res);
                                return false;
@@ -541,8 +530,8 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
                }
                else
                {
-                       fprintf(stderr, _("%s: could not send replication command \"%s\": %s"),
-                                       progname, query->data, PQerrorMessage(conn));
+                       pg_log_error("could not send replication command \"%s\": %s",
+                                                query->data, PQerrorMessage(conn));
 
                        destroyPQExpBuffer(query);
                        PQclear(res);
@@ -552,10 +541,9 @@ CreateReplicationSlot(PGconn *conn, const char *slot_name, const char *plugin,
 
        if (PQntuples(res) != 1 || PQnfields(res) != 4)
        {
-               fprintf(stderr,
-                               _("%s: could not create replication slot \"%s\": got %d rows and %d fields, expected %d rows and %d fields\n"),
-                               progname, slot_name,
-                               PQntuples(res), PQnfields(res), 1, 4);
+               pg_log_error("could not create replication slot \"%s\": got %d rows and %d fields, expected %d rows and %d fields",
+                                        slot_name,
+                                        PQntuples(res), PQnfields(res), 1, 4);
 
                destroyPQExpBuffer(query);
                PQclear(res);
@@ -587,8 +575,8 @@ DropReplicationSlot(PGconn *conn, const char *slot_name)
        res = PQexec(conn, query->data);
        if (PQresultStatus(res) != PGRES_COMMAND_OK)
        {
-               fprintf(stderr, _("%s: could not send replication command \"%s\": %s"),
-                               progname, query->data, PQerrorMessage(conn));
+               pg_log_error("could not send replication command \"%s\": %s",
+                                        query->data, PQerrorMessage(conn));
 
                destroyPQExpBuffer(query);
                PQclear(res);
@@ -597,10 +585,9 @@ DropReplicationSlot(PGconn *conn, const char *slot_name)
 
        if (PQntuples(res) != 0 || PQnfields(res) != 0)
        {
-               fprintf(stderr,
-                               _("%s: could not drop replication slot \"%s\": got %d rows and %d fields, expected %d rows and %d fields\n"),
-                               progname, slot_name,
-                               PQntuples(res), PQnfields(res), 0, 0);
+               pg_log_error("could not drop replication slot \"%s\": got %d rows and %d fields, expected %d rows and %d fields",
+                                        slot_name,
+                                        PQntuples(res), PQnfields(res), 0, 0);
 
                destroyPQExpBuffer(query);
                PQclear(res);
index 165b3a1e896793340ee68d53b63ce64150af8d23..83b520898beff1961041e9c0a440a67277907d55 100644 (file)
@@ -155,8 +155,8 @@ dir_open_for_write(const char *pathname, const char *temp_suffix, size_t pad_to_
         */
        if (dir_data->sync)
        {
-               if (fsync_fname(tmppath, false, progname) != 0 ||
-                       fsync_parent_path(tmppath, progname) != 0)
+               if (fsync_fname(tmppath, false) != 0 ||
+                       fsync_parent_path(tmppath) != 0)
                {
 #ifdef HAVE_LIBZ
                        if (dir_data->compression > 0)
@@ -244,7 +244,7 @@ dir_close(Walfile f, WalCloseMethod method)
                        snprintf(tmppath2, sizeof(tmppath2), "%s/%s%s",
                                         dir_data->basedir, df->pathname,
                                         dir_data->compression > 0 ? ".gz" : "");
-                       r = durable_rename(tmppath, tmppath2, progname);
+                       r = durable_rename(tmppath, tmppath2);
                }
                else if (method == CLOSE_UNLINK)
                {
@@ -264,9 +264,9 @@ dir_close(Walfile f, WalCloseMethod method)
                         */
                        if (dir_data->sync)
                        {
-                               r = fsync_fname(df->fullpath, false, progname);
+                               r = fsync_fname(df->fullpath, false);
                                if (r == 0)
-                                       r = fsync_parent_path(df->fullpath, progname);
+                                       r = fsync_parent_path(df->fullpath);
                        }
                }
        }
@@ -339,7 +339,7 @@ dir_finish(void)
                 * Files are fsynced when they are closed, but we need to fsync the
                 * directory entry here as well.
                 */
-               if (fsync_fname(dir_data->basedir, true, progname) != 0)
+               if (fsync_fname(dir_data->basedir, true) != 0)
                        return false;
        }
        return true;
@@ -970,9 +970,9 @@ tar_finish(void)
 
        if (tar_data->sync)
        {
-               if (fsync_fname(tar_data->tarfilename, false, progname) != 0)
+               if (fsync_fname(tar_data->tarfilename, false) != 0)
                        return false;
-               if (fsync_parent_path(tar_data->tarfilename, progname) != 0)
+               if (fsync_parent_path(tar_data->tarfilename) != 0)
                        return false;
        }
 
index 278b7a0f2ec04ff128063ea066216201a58106a5..13a25f5e3346d16817ad515ddac57556fb944205 100644 (file)
@@ -15,11 +15,13 @@ subdir = src/bin/pg_checksums
 top_builddir = ../../..
 include $(top_builddir)/src/Makefile.global
 
+LDFLAGS_INTERNAL += -L$(top_builddir)/src/fe_utils -lpgfeutils
+
 OBJS= pg_checksums.o $(WIN32RES)
 
 all: pg_checksums
 
-pg_checksums: $(OBJS) | submake-libpgport
+pg_checksums: $(OBJS) | submake-libpgport submake-libpgfeutils
        $(CC) $(CFLAGS) $^ $(LDFLAGS) $(LDFLAGS_EX) $(LIBS) -o $@$(X)
 
 install: all installdirs
index 2748b18ef72b592824b49388a9b7bf1c7a7d8027..372e88947299b8ab3db41eb075ee4e4d1406faf3 100644 (file)
@@ -1,4 +1,6 @@
 # src/bin/pg_checksums/nls.mk
 CATALOG_NAME     = pg_checksums
 AVAIL_LANGUAGES  =
-GETTEXT_FILES    = pg_checksums.c
+GETTEXT_FILES    = $(FRONTEND_COMMON_GETTEXT_FILES) pg_checksums.c
+GETTEXT_TRIGGERS = $(FRONTEND_COMMON_GETTEXT_TRIGGERS)
+GETTEXT_FLAGS    = $(FRONTEND_COMMON_GETTEXT_FLAGS)
index 5c185ebed8412f6928b69e0766279640dfa35afd..c7d26397f1d76e9a991725782fa1ffe61fdfd549 100644 (file)
@@ -22,6 +22,7 @@
 #include "common/controldata_utils.h"
 #include "common/file_perm.h"
 #include "common/file_utils.h"
+#include "fe_utils/logging.h"
 #include "getopt_long.h"
 #include "pg_getopt.h"
 #include "storage/bufpage.h"
@@ -126,8 +127,7 @@ scan_file(const char *fn, BlockNumber segmentno)
 
        if (f < 0)
        {
-               fprintf(stderr, _("%s: could not open file \"%s\": %s\n"),
-                               progname, fn, strerror(errno));
+               pg_log_error("could not open file \"%s\": %m", fn);
                exit(1);
        }
 
@@ -142,8 +142,8 @@ scan_file(const char *fn, BlockNumber segmentno)
                        break;
                if (r != BLCKSZ)
                {
-                       fprintf(stderr, _("%s: could not read block %u in file \"%s\": read %d of %d\n"),
-                                       progname, blockno, fn, r, BLCKSZ);
+                       pg_log_error("could not read block %u in file \"%s\": read %d of %d",
+                                                blockno, fn, r, BLCKSZ);
                        exit(1);
                }
                blocks++;
@@ -158,8 +158,8 @@ scan_file(const char *fn, BlockNumber segmentno)
                        if (csum != header->pd_checksum)
                        {
                                if (ControlFile->data_checksum_version == PG_DATA_CHECKSUM_VERSION)
-                                       fprintf(stderr, _("%s: checksum verification failed in file \"%s\", block %u: calculated checksum %X but block contains %X\n"),
-                                                       progname, fn, blockno, csum, header->pd_checksum);
+                                       pg_log_error("checksum verification failed in file \"%s\", block %u: calculated checksum %X but block contains %X",
+                                                                fn, blockno, csum, header->pd_checksum);
                                badblocks++;
                        }
                }
@@ -171,15 +171,15 @@ scan_file(const char *fn, BlockNumber segmentno)
                        /* Seek back to beginning of block */
                        if (lseek(f, -BLCKSZ, SEEK_CUR) < 0)
                        {
-                               fprintf(stderr, _("%s: seek failed for block %d in file \"%s\": %s\n"), progname, blockno, fn, strerror(errno));
+                               pg_log_error("seek failed for block %d in file \"%s\": %m", blockno, fn);
                                exit(1);
                        }
 
                        /* Write block with checksum */
                        if (write(f, buf.data, BLCKSZ) != BLCKSZ)
                        {
-                               fprintf(stderr, _("%s: could not update checksum of block %d in file \"%s\": %s\n"),
-                                               progname, blockno, fn, strerror(errno));
+                               pg_log_error("could not update checksum of block %d in file \"%s\": %m",
+                                                        blockno, fn);
                                exit(1);
                        }
                }
@@ -188,11 +188,9 @@ scan_file(const char *fn, BlockNumber segmentno)
        if (verbose)
        {
                if (mode == PG_MODE_CHECK)
-                       fprintf(stderr,
-                                       _("%s: checksums verified in file \"%s\"\n"), progname, fn);
+                       pg_log_info("checksums verified in file \"%s\"", fn);
                if (mode == PG_MODE_ENABLE)
-                       fprintf(stderr,
-                                       _("%s: checksums enabled in file \"%s\"\n"), progname, fn);
+                       pg_log_info("checksums enabled in file \"%s\"", fn);
        }
 
        close(f);
@@ -209,8 +207,7 @@ scan_directory(const char *basedir, const char *subdir)
        dir = opendir(path);
        if (!dir)
        {
-               fprintf(stderr, _("%s: could not open directory \"%s\": %s\n"),
-                               progname, path, strerror(errno));
+               pg_log_error("could not open directory \"%s\": %m", path);
                exit(1);
        }
        while ((de = readdir(dir)) != NULL)
@@ -237,8 +234,7 @@ scan_directory(const char *basedir, const char *subdir)
                snprintf(fn, sizeof(fn), "%s/%s", path, de->d_name);
                if (lstat(fn, &st) < 0)
                {
-                       fprintf(stderr, _("%s: could not stat file \"%s\": %s\n"),
-                                       progname, fn, strerror(errno));
+                       pg_log_error("could not stat file \"%s\": %m", fn);
                        exit(1);
                }
                if (S_ISREG(st.st_mode))
@@ -265,8 +261,8 @@ scan_directory(const char *basedir, const char *subdir)
                                segmentno = atoi(segmentpath);
                                if (segmentno == 0)
                                {
-                                       fprintf(stderr, _("%s: invalid segment number %d in file name \"%s\"\n"),
-                                                       progname, segmentno, fn);
+                                       pg_log_error("invalid segment number %d in file name \"%s\"",
+                                                                segmentno, fn);
                                        exit(1);
                                }
                        }
@@ -309,8 +305,8 @@ main(int argc, char *argv[])
        int                     option_index;
        bool            crc_ok;
 
+       pg_logging_init(argv[0]);
        set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_checksums"));
-
        progname = get_progname(argv[0]);
 
        if (argc > 1)
@@ -352,7 +348,7 @@ main(int argc, char *argv[])
                        case 'r':
                                if (atoi(optarg) == 0)
                                {
-                                       fprintf(stderr, _("%s: invalid relfilenode specification, must be numeric: %s\n"), progname, optarg);
+                                       pg_log_error("invalid relfilenode specification, must be numeric: %s", optarg);
                                        exit(1);
                                }
                                only_relfilenode = pstrdup(optarg);
@@ -373,7 +369,7 @@ main(int argc, char *argv[])
                /* If no DataDir was specified, and none could be found, error out */
                if (DataDir == NULL)
                {
-                       fprintf(stderr, _("%s: no data directory specified\n"), progname);
+                       pg_log_error("no data directory specified");
                        fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
                        exit(1);
                }
@@ -382,8 +378,8 @@ main(int argc, char *argv[])
        /* Complain if any arguments remain */
        if (optind < argc)
        {
-               fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
-                               progname, argv[optind]);
+               pg_log_error("too many command-line arguments (first is \"%s\")",
+                                        argv[optind]);
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                progname);
                exit(1);
@@ -392,31 +388,29 @@ main(int argc, char *argv[])
        /* Relfilenode checking only works in --check mode */
        if (mode != PG_MODE_CHECK && only_relfilenode)
        {
-               fprintf(stderr, _("%s: relfilenode option only possible with --check\n"), progname);
+               pg_log_error("relfilenode option only possible with --check");
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                progname);
                exit(1);
        }
 
        /* Check if cluster is running */
-       ControlFile = get_controlfile(DataDir, progname, &crc_ok);
+       ControlFile = get_controlfile(DataDir, &crc_ok);
        if (!crc_ok)
        {
-               fprintf(stderr, _("%s: pg_control CRC value is incorrect\n"), progname);
+               pg_log_error("pg_control CRC value is incorrect");
                exit(1);
        }
 
        if (ControlFile->pg_control_version != PG_CONTROL_VERSION)
        {
-               fprintf(stderr, _("%s: cluster is not compatible with this version of pg_checksums\n"),
-                               progname);
+               pg_log_error("cluster is not compatible with this version of pg_checksums");
                exit(1);
        }
 
        if (ControlFile->blcksz != BLCKSZ)
        {
-               fprintf(stderr, _("%s: database cluster is not compatible.\n"),
-                               progname);
+               pg_log_error("database cluster is not compatible");
                fprintf(stderr, _("The database cluster was initialized with block size %u, but pg_checksums was compiled with block size %u.\n"),
                                ControlFile->blcksz, BLCKSZ);
                exit(1);
@@ -425,28 +419,28 @@ main(int argc, char *argv[])
        if (ControlFile->state != DB_SHUTDOWNED &&
                ControlFile->state != DB_SHUTDOWNED_IN_RECOVERY)
        {
-               fprintf(stderr, _("%s: cluster must be shut down\n"), progname);
+               pg_log_error("cluster must be shut down");
                exit(1);
        }
 
        if (ControlFile->data_checksum_version == 0 &&
                mode == PG_MODE_CHECK)
        {
-               fprintf(stderr, _("%s: data checksums are not enabled in cluster\n"), progname);
+               pg_log_error("data checksums are not enabled in cluster");
                exit(1);
        }
 
        if (ControlFile->data_checksum_version == 0 &&
                mode == PG_MODE_DISABLE)
        {
-               fprintf(stderr, _("%s: data checksums are already disabled in cluster\n"), progname);
+               pg_log_error("data checksums are already disabled in cluster");
                exit(1);
        }
 
        if (ControlFile->data_checksum_version > 0 &&
                mode == PG_MODE_ENABLE)
        {
-               fprintf(stderr, _("%s: data checksums are already enabled in cluster\n"), progname);
+               pg_log_error("data checksums are already enabled in cluster");
                exit(1);
        }
 
@@ -482,12 +476,12 @@ main(int argc, char *argv[])
 
                if (do_sync)
                {
-                       printf(_("Syncing data directory\n"));
-                       fsync_pgdata(DataDir, progname, PG_VERSION_NUM);
+                       pg_log_info("syncing data directory");
+                       fsync_pgdata(DataDir, PG_VERSION_NUM);
                }
 
-               printf(_("Updating control file\n"));
-               update_controlfile(DataDir, progname, ControlFile, do_sync);
+               pg_log_info("updating control file");
+               update_controlfile(DataDir, ControlFile, do_sync);
 
                if (verbose)
                        printf(_("Data checksum version: %d\n"), ControlFile->data_checksum_version);
index 2d5c56213182b323066b3add0036b5ced78ac078..4d9c1370fe73dbdd30f55731db440fc2df5a3d4e 100644 (file)
@@ -15,11 +15,13 @@ subdir = src/bin/pg_controldata
 top_builddir = ../../..
 include $(top_builddir)/src/Makefile.global
 
+LDFLAGS_INTERNAL += -L$(top_builddir)/src/fe_utils -lpgfeutils
+
 OBJS= pg_controldata.o $(WIN32RES)
 
 all: pg_controldata
 
-pg_controldata: $(OBJS) | submake-libpgport
+pg_controldata: $(OBJS) | submake-libpgport submake-libpgfeutils
        $(CC) $(CFLAGS) $^ $(LDFLAGS) $(LDFLAGS_EX) $(LIBS) -o $@$(X)
 
 install: all installdirs
index 9a17d0f9c0f8d9a6415750f62619bb86dd392e9a..a674f52f0b8f321c145bf96abd3235e4ddb733f4 100644 (file)
@@ -25,6 +25,7 @@
 #include "access/xlog_internal.h"
 #include "catalog/pg_control.h"
 #include "common/controldata_utils.h"
+#include "fe_utils/logging.h"
 #include "pg_getopt.h"
 #include "getopt_long.h"
 
@@ -107,8 +108,8 @@ main(int argc, char *argv[])
        int                     i;
        int                     WalSegSz;
 
+       pg_logging_init(argv[0]);
        set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_controldata"));
-
        progname = get_progname(argv[0]);
 
        if (argc > 1)
@@ -150,8 +151,8 @@ main(int argc, char *argv[])
        /* Complain if any arguments remain */
        if (optind < argc)
        {
-               fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
-                               progname, argv[optind]);
+               pg_log_error("too many command-line arguments (first is \"%s\")",
+                                        argv[optind]);
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
                                progname);
                exit(1);
@@ -159,13 +160,13 @@ main(int argc, char *argv[])
 
        if (DataDir == NULL)
        {
-               fprintf(stderr, _("%s: no data directory specified\n"), progname);
+               pg_log_error("no data directory specified");
                fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
                exit(1);
        }
 
        /* get a copy of the control file */
-       ControlFile = get_controlfile(DataDir, progname, &crc_ok);
+       ControlFile = get_controlfile(DataDir, &crc_ok);
        if (!crc_ok)
                printf(_("WARNING: Calculated CRC checksum does not match value stored in file.\n"
                                 "Either the file is corrupt, or it has a different layout than this program\n"
index 83cbf97ed8815450ee971d8726eaaa73e4cdcc58..b931b14a3f566459663669efc08a53d456fa3ff5 100644 (file)
@@ -16,6 +16,8 @@ subdir = src/bin/pg_ctl
 top_builddir = ../../..
 include $(top_builddir)/src/Makefile.global
 
+LDFLAGS_INTERNAL += -L$(top_builddir)/src/fe_utils -lpgfeutils
+
 # On Windows, we need to link with libpq, just for use of pqexpbuffer;
 # but let's not pull that in on platforms where we don't need it.
 ifeq ($(PORTNAME), win32)
@@ -28,7 +30,7 @@ OBJS= pg_ctl.o $(WIN32RES)
 
 all: pg_ctl
 
-pg_ctl: $(OBJS) | submake-libpgport $(SUBMAKE_LIBPQ)
+pg_ctl: $(OBJS) | submake-libpgport submake-libpgfeutils $(SUBMAKE_LIBPQ)
        $(CC) $(CFLAGS) $(OBJS) $(LDFLAGS) $(LDFLAGS_EX) $(LIBS) -o $@$(X)
 
 install: all installdirs
index c82a702ffa64f394d62d9c66a4dbae88c20aec9b..febb076ee6f8c9fde94ec04df4aff75c64827941 100644 (file)
@@ -26,6 +26,7 @@
 #include "catalog/pg_control.h"
 #include "common/controldata_utils.h"
 #include "common/file_perm.h"
+#include "fe_utils/logging.h"
 #include "getopt_long.h"
 #include "utils/pidfile.h"
 
@@ -2231,7 +2232,7 @@ get_control_dbstate(void)
 {
        DBState         ret;
        bool            crc_ok;
-       ControlFileData *control_file_data = get_controlfile(pg_data, progname, &crc_ok);
+       ControlFileData *control_file_data = get_controlfile(pg_data, &crc_ok);
 
        if (!crc_ok)
        {
@@ -2268,10 +2269,7 @@ main(int argc, char **argv)
        int                     c;
        pgpid_t         killproc = 0;
 
-#ifdef WIN32
-       setvbuf(stderr, NULL, _IONBF, 0);
-#endif
-
+       pg_logging_init(argv[0]);
        progname = get_progname(argv[0]);
        set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_ctl"));
        start_time = time(NULL);
index 249706fe57c0827434ceb6c5515d7a19c523bc13..5958f42a847545e9dce4bffed6cdbb1218bbd85b 100644 (file)
@@ -22,6 +22,7 @@
 #include <ctype.h>
 
 #include "catalog/pg_class_d.h"
+#include "fe_utils/logging.h"
 #include "fe_utils/string_utils.h"
 
 
@@ -120,17 +121,14 @@ getSchemaData(Archive *fout, int *numTablesPtr)
         * extension membership needs to be consultable during decisions about
         * whether other objects are to be dumped.
         */
-       if (g_verbose)
-               write_msg(NULL, "reading extensions\n");
+       pg_log_info("reading extensions");
        extinfo = getExtensions(fout, &numExtensions);
        extinfoindex = buildIndexArray(extinfo, numExtensions, sizeof(ExtensionInfo));
 
-       if (g_verbose)
-               write_msg(NULL, "identifying extension members\n");
+       pg_log_info("identifying extension members");
        getExtensionMembership(fout, extinfo, numExtensions);
 
-       if (g_verbose)
-               write_msg(NULL, "reading schemas\n");
+       pg_log_info("reading schemas");
        nspinfo = getNamespaces(fout, &numNamespaces);
        nspinfoindex = buildIndexArray(nspinfo, numNamespaces, sizeof(NamespaceInfo));
 
@@ -140,160 +138,124 @@ getSchemaData(Archive *fout, int *numTablesPtr)
         * However, we have to do getNamespaces first because the tables get
         * linked to their containing namespaces during getTables.
         */
-       if (g_verbose)
-               write_msg(NULL, "reading user-defined tables\n");
+       pg_log_info("reading user-defined tables");
        tblinfo = getTables(fout, &numTables);
        tblinfoindex = buildIndexArray(tblinfo, numTables, sizeof(TableInfo));
 
        /* Do this after we've built tblinfoindex */
        getOwnedSeqs(fout, tblinfo, numTables);
 
-       if (g_verbose)
-               write_msg(NULL, "reading user-defined functions\n");
+       pg_log_info("reading user-defined functions");
        funinfo = getFuncs(fout, &numFuncs);
        funinfoindex = buildIndexArray(funinfo, numFuncs, sizeof(FuncInfo));
 
        /* this must be after getTables and getFuncs */
-       if (g_verbose)
-               write_msg(NULL, "reading user-defined types\n");
+       pg_log_info("reading user-defined types");
        typinfo = getTypes(fout, &numTypes);
        typinfoindex = buildIndexArray(typinfo, numTypes, sizeof(TypeInfo));
 
        /* this must be after getFuncs, too */
-       if (g_verbose)
-               write_msg(NULL, "reading procedural languages\n");
+       pg_log_info("reading procedural languages");
        getProcLangs(fout, &numProcLangs);
 
-       if (g_verbose)
-               write_msg(NULL, "reading user-defined aggregate functions\n");
+       pg_log_info("reading user-defined aggregate functions");
        getAggregates(fout, &numAggregates);
 
-       if (g_verbose)
-               write_msg(NULL, "reading user-defined operators\n");
+       pg_log_info("reading user-defined operators");
        oprinfo = getOperators(fout, &numOperators);
        oprinfoindex = buildIndexArray(oprinfo, numOperators, sizeof(OprInfo));
 
-       if (g_verbose)
-               write_msg(NULL, "reading user-defined access methods\n");
+       pg_log_info("reading user-defined access methods");
        getAccessMethods(fout, &numAccessMethods);
 
-       if (g_verbose)
-               write_msg(NULL, "reading user-defined operator classes\n");
+       pg_log_info("reading user-defined operator classes");
        getOpclasses(fout, &numOpclasses);
 
-       if (g_verbose)
-               write_msg(NULL, "reading user-defined operator families\n");
+       pg_log_info("reading user-defined operator families");
        getOpfamilies(fout, &numOpfamilies);
 
-       if (g_verbose)
-               write_msg(NULL, "reading user-defined text search parsers\n");
+       pg_log_info("reading user-defined text search parsers");
        getTSParsers(fout, &numTSParsers);
 
-       if (g_verbose)
-               write_msg(NULL, "reading user-defined text search templates\n");
+       pg_log_info("reading user-defined text search templates");
        getTSTemplates(fout, &numTSTemplates);
 
-       if (g_verbose)
-               write_msg(NULL, "reading user-defined text search dictionaries\n");
+       pg_log_info("reading user-defined text search dictionaries");
        getTSDictionaries(fout, &numTSDicts);
 
-       if (g_verbose)
-               write_msg(NULL, "reading user-defined text search configurations\n");
+       pg_log_info("reading user-defined text search configurations");
        getTSConfigurations(fout, &numTSConfigs);
 
-       if (g_verbose)
-               write_msg(NULL, "reading user-defined foreign-data wrappers\n");
+       pg_log_info("reading user-defined foreign-data wrappers");
        getForeignDataWrappers(fout, &numForeignDataWrappers);
 
-       if (g_verbose)
-               write_msg(NULL, "reading user-defined foreign servers\n");
+       pg_log_info("reading user-defined foreign servers");
        getForeignServers(fout, &numForeignServers);
 
-       if (g_verbose)
-               write_msg(NULL, "reading default privileges\n");
+       pg_log_info("reading default privileges");
        getDefaultACLs(fout, &numDefaultACLs);
 
-       if (g_verbose)
-               write_msg(NULL, "reading user-defined collations\n");
+       pg_log_info("reading user-defined collations");
        collinfo = getCollations(fout, &numCollations);
        collinfoindex = buildIndexArray(collinfo, numCollations, sizeof(CollInfo));
 
-       if (g_verbose)
-               write_msg(NULL, "reading user-defined conversions\n");
+       pg_log_info("reading user-defined conversions");
        getConversions(fout, &numConversions);
 
-       if (g_verbose)
-               write_msg(NULL, "reading type casts\n");
+       pg_log_info("reading type casts");
        getCasts(fout, &numCasts);
 
-       if (g_verbose)
-               write_msg(NULL, "reading transforms\n");
+       pg_log_info("reading transforms");
        getTransforms(fout, &numTransforms);
 
-       if (g_verbose)
-               write_msg(NULL, "reading table inheritance information\n");
+       pg_log_info("reading table inheritance information");
        inhinfo = getInherits(fout, &numInherits);
 
-       if (g_verbose)
-               write_msg(NULL, "reading event triggers\n");
+       pg_log_info("reading event triggers");
        getEventTriggers(fout, &numEventTriggers);
 
        /* Identify extension configuration tables that should be dumped */
-       if (g_verbose)
-               write_msg(NULL, "finding extension tables\n");
+       pg_log_info("finding extension tables");
        processExtensionTables(fout, extinfo, numExtensions);
 
        /* Link tables to parents, mark parents of target tables interesting */
-       if (g_verbose)
-               write_msg(NULL, "finding inheritance relationships\n");
+       pg_log_info("finding inheritance relationships");
        flagInhTables(fout, tblinfo, numTables, inhinfo, numInherits);
 
-       if (g_verbose)
-               write_msg(NULL, "reading column info for interesting tables\n");
+       pg_log_info("reading column info for interesting tables");
        getTableAttrs(fout, tblinfo, numTables);
 
-       if (g_verbose)
-               write_msg(NULL, "flagging inherited columns in subtables\n");
+       pg_log_info("flagging inherited columns in subtables");
        flagInhAttrs(fout->dopt, tblinfo, numTables);
 
-       if (g_verbose)
-               write_msg(NULL, "reading indexes\n");
+       pg_log_info("reading indexes");
        getIndexes(fout, tblinfo, numTables);
 
-       if (g_verbose)
-               write_msg(NULL, "flagging indexes in partitioned tables\n");
+       pg_log_info("flagging indexes in partitioned tables");
        flagInhIndexes(fout, tblinfo, numTables);
 
-       if (g_verbose)
-               write_msg(NULL, "reading extended statistics\n");
+       pg_log_info("reading extended statistics");
        getExtendedStatistics(fout);
 
-       if (g_verbose)
-               write_msg(NULL, "reading constraints\n");
+       pg_log_info("reading constraints");
        getConstraints(fout, tblinfo, numTables);
 
-       if (g_verbose)
-               write_msg(NULL, "reading triggers\n");
+       pg_log_info("reading triggers");
        getTriggers(fout, tblinfo, numTables);
 
-       if (g_verbose)
-               write_msg(NULL, "reading rewrite rules\n");
+       pg_log_info("reading rewrite rules");
        getRules(fout, &numRules);
 
-       if (g_verbose)
-               write_msg(NULL, "reading policies\n");
+       pg_log_info("reading policies");
        getPolicies(fout, tblinfo, numTables);
 
-       if (g_verbose)
-               write_msg(NULL, "reading publications\n");
+       pg_log_info("reading publications");
        getPublications(fout);
 
-       if (g_verbose)
-               write_msg(NULL, "reading publication membership\n");
+       pg_log_info("reading publication membership");
        getPublicationTables(fout, tblinfo, numTables);
 
-       if (g_verbose)
-               write_msg(NULL, "reading subscriptions\n");
+       pg_log_info("reading subscriptions");
        getSubscriptions(fout);
 
        *numTablesPtr = numTables;
@@ -1059,7 +1021,7 @@ findParentsByOid(TableInfo *self,
                                parent = findTableByOid(inhinfo[i].inhparent);
                                if (parent == NULL)
                                {
-                                       write_msg(NULL, "failed sanity check, parent OID %u of table \"%s\" (OID %u) not found\n",
+                                       pg_log_error("failed sanity check, parent OID %u of table \"%s\" (OID %u) not found",
                                                          inhinfo[i].inhparent,
                                                          self->dobj.name,
                                                          oid);
@@ -1101,7 +1063,7 @@ parseOidArray(const char *str, Oid *array, int arraysize)
                        {
                                if (argNum >= arraysize)
                                {
-                                       write_msg(NULL, "could not parse numeric array \"%s\": too many numbers\n", str);
+                                       pg_log_error("could not parse numeric array \"%s\": too many numbers", str);
                                        exit_nicely(1);
                                }
                                temp[j] = '\0';
@@ -1116,7 +1078,7 @@ parseOidArray(const char *str, Oid *array, int arraysize)
                        if (!(isdigit((unsigned char) s) || s == '-') ||
                                j >= sizeof(temp) - 1)
                        {
-                               write_msg(NULL, "could not parse numeric array \"%s\": invalid character in number\n", str);
+                               pg_log_error("could not parse numeric array \"%s\": invalid character in number", str);
                                exit_nicely(1);
                        }
                        temp[j++] = s;
index d904ec62ad1f175d1c1f74fc110faf3f0cc2f81e..a0d7644a8adc52c8c463fde9c17acf33b0db026e 100644 (file)
@@ -74,9 +74,6 @@ struct CompressorState
 #endif
 };
 
-/* translator: this is a module name */
-static const char *modulename = gettext_noop("compress_io");
-
 static void ParseCompressionOption(int compression, CompressionAlgorithm *alg,
                                           int *level);
 
@@ -111,8 +108,7 @@ ParseCompressionOption(int compression, CompressionAlgorithm *alg, int *level)
                *alg = COMPR_ALG_NONE;
        else
        {
-               exit_horribly(modulename, "invalid compression code: %d\n",
-                                         compression);
+               fatal("invalid compression code: %d", compression);
                *alg = COMPR_ALG_NONE;  /* keep compiler quiet */
        }
 
@@ -135,7 +131,7 @@ AllocateCompressor(int compression, WriteFunc writeF)
 
 #ifndef HAVE_LIBZ
        if (alg == COMPR_ALG_LIBZ)
-               exit_horribly(modulename, "not built with zlib support\n");
+               fatal("not built with zlib support");
 #endif
 
        cs = (CompressorState *) pg_malloc0(sizeof(CompressorState));
@@ -171,7 +167,7 @@ ReadDataFromArchive(ArchiveHandle *AH, int compression, ReadFunc readF)
 #ifdef HAVE_LIBZ
                ReadDataFromArchiveZlib(AH, readF);
 #else
-               exit_horribly(modulename, "not built with zlib support\n");
+               fatal("not built with zlib support");
 #endif
        }
 }
@@ -189,7 +185,7 @@ WriteDataToArchive(ArchiveHandle *AH, CompressorState *cs,
 #ifdef HAVE_LIBZ
                        WriteDataToArchiveZlib(AH, cs, data, dLen);
 #else
-                       exit_horribly(modulename, "not built with zlib support\n");
+                       fatal("not built with zlib support");
 #endif
                        break;
                case COMPR_ALG_NONE:
@@ -238,8 +234,7 @@ InitCompressorZlib(CompressorState *cs, int level)
        cs->zlibOutSize = ZLIB_OUT_SIZE;
 
        if (deflateInit(zp, level) != Z_OK)
-               exit_horribly(modulename,
-                                         "could not initialize compression library: %s\n",
+               fatal("could not initialize compression library: %s",
                                          zp->msg);
 
        /* Just be paranoid - maybe End is called after Start, with no Write */
@@ -259,8 +254,7 @@ EndCompressorZlib(ArchiveHandle *AH, CompressorState *cs)
        DeflateCompressorZlib(AH, cs, true);
 
        if (deflateEnd(zp) != Z_OK)
-               exit_horribly(modulename,
-                                         "could not close compression stream: %s\n", zp->msg);
+               fatal("could not close compression stream: %s", zp->msg);
 
        free(cs->zlibOut);
        free(cs->zp);
@@ -277,8 +271,7 @@ DeflateCompressorZlib(ArchiveHandle *AH, CompressorState *cs, bool flush)
        {
                res = deflate(zp, flush ? Z_FINISH : Z_NO_FLUSH);
                if (res == Z_STREAM_ERROR)
-                       exit_horribly(modulename,
-                                                 "could not compress data: %s\n", zp->msg);
+                       fatal("could not compress data: %s", zp->msg);
                if ((flush && (zp->avail_out < cs->zlibOutSize))
                        || (zp->avail_out == 0)
                        || (zp->avail_in != 0)
@@ -340,8 +333,7 @@ ReadDataFromArchiveZlib(ArchiveHandle *AH, ReadFunc readF)
        out = pg_malloc(ZLIB_OUT_SIZE + 1);
 
        if (inflateInit(zp) != Z_OK)
-               exit_horribly(modulename,
-                                         "could not initialize compression library: %s\n",
+               fatal("could not initialize compression library: %s",
                                          zp->msg);
 
        /* no minimal chunk size for zlib */
@@ -357,8 +349,7 @@ ReadDataFromArchiveZlib(ArchiveHandle *AH, ReadFunc readF)
 
                        res = inflate(zp, 0);
                        if (res != Z_OK && res != Z_STREAM_END)
-                               exit_horribly(modulename,
-                                                         "could not uncompress data: %s\n", zp->msg);
+                               fatal("could not uncompress data: %s", zp->msg);
 
                        out[ZLIB_OUT_SIZE - zp->avail_out] = '\0';
                        ahwrite(out, 1, ZLIB_OUT_SIZE - zp->avail_out, AH);
@@ -373,16 +364,14 @@ ReadDataFromArchiveZlib(ArchiveHandle *AH, ReadFunc readF)
                zp->avail_out = ZLIB_OUT_SIZE;
                res = inflate(zp, 0);
                if (res != Z_OK && res != Z_STREAM_END)
-                       exit_horribly(modulename,
-                                                 "could not uncompress data: %s\n", zp->msg);
+                       fatal("could not uncompress data: %s", zp->msg);
 
                out[ZLIB_OUT_SIZE - zp->avail_out] = '\0';
                ahwrite(out, 1, ZLIB_OUT_SIZE - zp->avail_out, AH);
        }
 
        if (inflateEnd(zp) != Z_OK)
-               exit_horribly(modulename,
-                                         "could not close compression library: %s\n", zp->msg);
+               fatal("could not close compression library: %s", zp->msg);
 
        free(buf);
        free(out);
@@ -516,7 +505,7 @@ cfopen_write(const char *path, const char *mode, int compression)
                fp = cfopen(fname, mode, compression);
                free_keep_errno(fname);
 #else
-               exit_horribly(modulename, "not built with zlib support\n");
+               fatal("not built with zlib support");
                fp = NULL;                              /* keep compiler quiet */
 #endif
        }
@@ -559,7 +548,7 @@ cfopen(const char *path, const char *mode, int compression)
                        fp = NULL;
                }
 #else
-               exit_horribly(modulename, "not built with zlib support\n");
+               fatal("not built with zlib support");
 #endif
        }
        else
@@ -596,8 +585,7 @@ cfread(void *ptr, int size, cfp *fp)
                        int                     errnum;
                        const char *errmsg = gzerror(fp->compressedfp, &errnum);
 
-                       exit_horribly(modulename,
-                                                 "could not read from input file: %s\n",
+                       fatal("could not read from input file: %s",
                                                  errnum == Z_ERRNO ? strerror(errno) : errmsg);
                }
        }
@@ -634,11 +622,9 @@ cfgetc(cfp *fp)
                if (ret == EOF)
                {
                        if (!gzeof(fp->compressedfp))
-                               exit_horribly(modulename,
-                                                         "could not read from input file: %s\n", strerror(errno));
+                               fatal("could not read from input file: %s", strerror(errno));
                        else
-                               exit_horribly(modulename,
-                                                         "could not read from input file: end of file\n");
+                               fatal("could not read from input file: end of file");
                }
        }
        else
index 37234717cb630aae596f9547cec314730ba34b18..8a53ad08ddba8fc9f031512bcae4981ce4ebff77 100644 (file)
@@ -1,7 +1,8 @@
 # src/bin/pg_dump/nls.mk
 CATALOG_NAME     = pg_dump
 AVAIL_LANGUAGES  = cs de es fr he it ja ko pl pt_BR ru sv tr zh_CN
-GETTEXT_FILES    = pg_backup_archiver.c pg_backup_db.c pg_backup_custom.c \
+GETTEXT_FILES    = $(FRONTEND_COMMON_GETTEXT_FILES) \
+                   pg_backup_archiver.c pg_backup_db.c pg_backup_custom.c \
                    pg_backup_null.c pg_backup_tar.c \
                    pg_backup_directory.c dumputils.c compress_io.c \
                    pg_dump.c common.c pg_dump_sort.c \
@@ -9,10 +10,9 @@ GETTEXT_FILES    = pg_backup_archiver.c pg_backup_db.c pg_backup_custom.c \
                    parallel.c parallel.h pg_backup_utils.c pg_backup_utils.h \
                    ../../common/exec.c ../../common/fe_memutils.c \
                    ../../common/wait_error.c
-GETTEXT_TRIGGERS = write_msg:2 exit_horribly:2 simple_prompt \
-                   ExecuteSqlCommand:3 ahlog:3 warn_or_exit_horribly:3
-GETTEXT_FLAGS  = \
-    write_msg:2:c-format \
-    exit_horribly:2:c-format \
-    ahlog:3:c-format \
-    warn_or_exit_horribly:3:c-format
+GETTEXT_TRIGGERS = $(FRONTEND_COMMON_GETTEXT_TRIGGERS) \
+                   fatal simple_prompt \
+                   ExecuteSqlCommand:3 warn_or_exit_horribly:3
+GETTEXT_FLAGS    = $(FRONTEND_COMMON_GETTEXT_FLAGS) \
+    fatal:1:c-format \
+    warn_or_exit_horribly:2:c-format
index 41aa78a953367cc6970d0f98fab81998d9e044e8..3dfdae3a579fcbc283d29bba577a46e7e1f3e9e4 100644 (file)
@@ -197,8 +197,6 @@ bool                parallel_init_done = false;
 DWORD          mainThreadId;
 #endif                                                 /* WIN32 */
 
-static const char *modulename = gettext_noop("parallel archiver");
-
 /* Local function prototypes */
 static ParallelSlot *GetMyPSlot(ParallelState *pstate);
 static void archive_close_connection(int code, void *arg);
@@ -262,7 +260,7 @@ init_parallel_dump_utils(void)
                err = WSAStartup(MAKEWORD(2, 2), &wsaData);
                if (err != 0)
                {
-                       fprintf(stderr, _("%s: WSAStartup failed: %d\n"), progname, err);
+                       pg_log_error("WSAStartup failed: %d", err);
                        exit_nicely(1);
                }
                /* ... and arrange to shut it down at exit */
@@ -404,8 +402,8 @@ archive_close_connection(int code, void *arg)
  * Forcibly shut down any remaining workers, waiting for them to finish.
  *
  * Note that we don't expect to come here during normal exit (the workers
- * should be long gone, and the ParallelState too).  We're only here in an
- * exit_horribly() situation, so intervening to cancel active commands is
+ * should be long gone, and the ParallelState too).  We're only here in a
+ * fatal() situation, so intervening to cancel active commands is
  * appropriate.
  */
 static void
@@ -697,7 +695,7 @@ consoleHandler(DWORD dwCtrlType)
 
                /*
                 * Report we're quitting, using nothing more complicated than
-                * write(2).  (We might be able to get away with using write_msg()
+                * write(2).  (We might be able to get away with using pg_log_*()
                 * here, but since we terminated other threads uncleanly above, it
                 * seems better to assume as little as possible.)
                 */
@@ -967,9 +965,7 @@ ParallelBackupStart(ArchiveHandle *AH)
 
                /* Create communication pipes for this worker */
                if (pgpipe(pipeMW) < 0 || pgpipe(pipeWM) < 0)
-                       exit_horribly(modulename,
-                                                 "could not create communication channels: %s\n",
-                                                 strerror(errno));
+                       fatal("could not create communication channels: %m");
 
                pstate->te[i] = NULL;   /* just for safety */
 
@@ -1032,9 +1028,7 @@ ParallelBackupStart(ArchiveHandle *AH)
                else if (pid < 0)
                {
                        /* fork failed */
-                       exit_horribly(modulename,
-                                                 "could not create worker process: %s\n",
-                                                 strerror(errno));
+                       fatal("could not create worker process: %m");
                }
 
                /* In Master after successful fork */
@@ -1163,8 +1157,7 @@ parseWorkerCommand(ArchiveHandle *AH, TocEntry **te, T_Action *act,
                Assert(*te != NULL);
        }
        else
-               exit_horribly(modulename,
-                                         "unrecognized command received from master: \"%s\"\n",
+               fatal("unrecognized command received from master: \"%s\"",
                                          msg);
 }
 
@@ -1207,8 +1200,7 @@ parseWorkerResponse(ArchiveHandle *AH, TocEntry *te,
                AH->public.n_errors += n_errors;
        }
        else
-               exit_horribly(modulename,
-                                         "invalid message received from worker: \"%s\"\n",
+               fatal("invalid message received from worker: \"%s\"",
                                          msg);
 
        return status;
@@ -1340,11 +1332,10 @@ lockTableForWorker(ArchiveHandle *AH, TocEntry *te)
        res = PQexec(AH->connection, query->data);
 
        if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
-               exit_horribly(modulename,
-                                         "could not obtain lock on relation \"%s\"\n"
-                                         "This usually means that someone requested an ACCESS EXCLUSIVE lock "
-                                         "on the table after the pg_dump parent process had gotten the "
-                                         "initial ACCESS SHARE lock on the table.\n", qualId);
+               fatal("could not obtain lock on relation \"%s\"\n"
+                         "This usually means that someone requested an ACCESS EXCLUSIVE lock "
+                         "on the table after the pg_dump parent process had gotten the "
+                         "initial ACCESS SHARE lock on the table.", qualId);
 
        PQclear(res);
        destroyPQExpBuffer(query);
@@ -1430,7 +1421,7 @@ ListenToWorkers(ArchiveHandle *AH, ParallelState *pstate, bool do_wait)
        {
                /* If do_wait is true, we must have detected EOF on some socket */
                if (do_wait)
-                       exit_horribly(modulename, "a worker process died unexpectedly\n");
+                       fatal("a worker process died unexpectedly");
                return false;
        }
 
@@ -1447,8 +1438,7 @@ ListenToWorkers(ArchiveHandle *AH, ParallelState *pstate, bool do_wait)
                pstate->te[worker] = NULL;
        }
        else
-               exit_horribly(modulename,
-                                         "invalid message received from worker: \"%s\"\n",
+               fatal("invalid message received from worker: \"%s\"",
                                          msg);
 
        /* Free the string returned from getMessageFromWorker */
@@ -1553,9 +1543,7 @@ sendMessageToMaster(int pipefd[2], const char *str)
        int                     len = strlen(str) + 1;
 
        if (pipewrite(pipefd[PIPE_WRITE], str, len) != len)
-               exit_horribly(modulename,
-                                         "could not write to the communication channel: %s\n",
-                                         strerror(errno));
+               fatal("could not write to the communication channel: %m");
 }
 
 /*
@@ -1632,7 +1620,7 @@ getMessageFromWorker(ParallelState *pstate, bool do_wait, int *worker)
        }
 
        if (i < 0)
-               exit_horribly(modulename, "select() failed: %s\n", strerror(errno));
+               fatal("select() failed: %m");
 
        for (i = 0; i < pstate->numWorkers; i++)
        {
@@ -1671,9 +1659,7 @@ sendMessageToWorker(ParallelState *pstate, int worker, const char *str)
 
        if (pipewrite(pstate->parallelSlot[worker].pipeWrite, str, len) != len)
        {
-               exit_horribly(modulename,
-                                         "could not write to the communication channel: %s\n",
-                                         strerror(errno));
+               fatal("could not write to the communication channel: %m");
        }
 }
 
@@ -1757,7 +1743,7 @@ pgpipe(int handles[2])
         */
        if ((s = socket(AF_INET, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
        {
-               write_msg(modulename, "pgpipe: could not create socket: error code %d\n",
+               pg_log_error("pgpipe: could not create socket: error code %d",
                                  WSAGetLastError());
                return -1;
        }
@@ -1768,21 +1754,21 @@ pgpipe(int handles[2])
        serv_addr.sin_addr.s_addr = pg_hton32(INADDR_LOOPBACK);
        if (bind(s, (SOCKADDR *) &serv_addr, len) == SOCKET_ERROR)
        {
-               write_msg(modulename, "pgpipe: could not bind: error code %d\n",
+               pg_log_error("pgpipe: could not bind: error code %d",
                                  WSAGetLastError());
                closesocket(s);
                return -1;
        }
        if (listen(s, 1) == SOCKET_ERROR)
        {
-               write_msg(modulename, "pgpipe: could not listen: error code %d\n",
+               pg_log_error("pgpipe: could not listen: error code %d",
                                  WSAGetLastError());
                closesocket(s);
                return -1;
        }
        if (getsockname(s, (SOCKADDR *) &serv_addr, &len) == SOCKET_ERROR)
        {
-               write_msg(modulename, "pgpipe: getsockname() failed: error code %d\n",
+               pg_log_error("pgpipe: getsockname() failed: error code %d",
                                  WSAGetLastError());
                closesocket(s);
                return -1;
@@ -1793,7 +1779,7 @@ pgpipe(int handles[2])
         */
        if ((tmp_sock = socket(AF_INET, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
        {
-               write_msg(modulename, "pgpipe: could not create second socket: error code %d\n",
+               pg_log_error("pgpipe: could not create second socket: error code %d",
                                  WSAGetLastError());
                closesocket(s);
                return -1;
@@ -1802,7 +1788,7 @@ pgpipe(int handles[2])
 
        if (connect(handles[1], (SOCKADDR *) &serv_addr, len) == SOCKET_ERROR)
        {
-               write_msg(modulename, "pgpipe: could not connect socket: error code %d\n",
+               pg_log_error("pgpipe: could not connect socket: error code %d",
                                  WSAGetLastError());
                closesocket(handles[1]);
                handles[1] = -1;
@@ -1811,7 +1797,7 @@ pgpipe(int handles[2])
        }
        if ((tmp_sock = accept(s, (SOCKADDR *) &serv_addr, &len)) == PGINVALID_SOCKET)
        {
-               write_msg(modulename, "pgpipe: could not accept connection: error code %d\n",
+               pg_log_error("pgpipe: could not accept connection: error code %d",
                                  WSAGetLastError());
                closesocket(handles[1]);
                handles[1] = -1;
index 6131cdda96c12167a0e8045cd2bc0006abfe7d70..1a75cd00cd92850c7b1bbbf257fdaaf235efe69a 100644 (file)
@@ -35,6 +35,7 @@
 #include "pg_backup_db.h"
 #include "pg_backup_utils.h"
 #include "dumputils.h"
+#include "fe_utils/logging.h"
 #include "fe_utils/string_utils.h"
 
 #include "libpq/libpq-fs.h"
@@ -67,9 +68,6 @@ typedef struct _parallelReadyList
        bool            sorted;                 /* are valid entries currently sorted? */
 } ParallelReadyList;
 
-/* translator: this is a module name */
-static const char *modulename = gettext_noop("archiver");
-
 
 static ArchiveHandle *_allocAH(const char *FileSpec, const ArchiveFormat fmt,
                 const int compression, bool dosync, ArchiveMode mode,
@@ -272,8 +270,7 @@ CloseArchive(Archive *AHX)
                res = fclose(AH->OF);
 
        if (res != 0)
-               exit_horribly(modulename, "could not close output file: %s\n",
-                                         strerror(errno));
+               fatal("could not close output file: %m");
 }
 
 /* Public */
@@ -317,19 +314,17 @@ ProcessArchiveRestoreOptions(Archive *AHX)
                                        break;
                                case SECTION_PRE_DATA:
                                        if (curSection != SECTION_PRE_DATA)
-                                               write_msg(modulename,
-                                                                 "WARNING: archive items not in correct section order\n");
+                                               pg_log_warning("archive items not in correct section order");
                                        break;
                                case SECTION_DATA:
                                        if (curSection == SECTION_POST_DATA)
-                                               write_msg(modulename,
-                                                                 "WARNING: archive items not in correct section order\n");
+                                               pg_log_warning("archive items not in correct section order");
                                        break;
                                case SECTION_POST_DATA:
                                        /* ok no matter which section we were in */
                                        break;
                                default:
-                                       exit_horribly(modulename, "unexpected section code %d\n",
+                                       fatal("unexpected section code %d",
                                                                  (int) te->section);
                                        break;
                        }
@@ -366,11 +361,11 @@ RestoreArchive(Archive *AHX)
        {
                /* We haven't got round to making this work for all archive formats */
                if (AH->ClonePtr == NULL || AH->ReopenPtr == NULL)
-                       exit_horribly(modulename, "parallel restore is not supported with this archive file format\n");
+                       fatal("parallel restore is not supported with this archive file format");
 
                /* Doesn't work if the archive represents dependencies as OIDs */
                if (AH->version < K_VERS_1_8)
-                       exit_horribly(modulename, "parallel restore is not supported with archives made by pre-8.0 pg_dump\n");
+                       fatal("parallel restore is not supported with archives made by pre-8.0 pg_dump");
 
                /*
                 * It's also not gonna work if we can't reopen the input file, so
@@ -388,7 +383,7 @@ RestoreArchive(Archive *AHX)
                for (te = AH->toc->next; te != AH->toc; te = te->next)
                {
                        if (te->hadDumper && (te->reqs & REQ_DATA) != 0)
-                               exit_horribly(modulename, "cannot restore from compressed archive (compression not supported in this installation)\n");
+                               fatal("cannot restore from compressed archive (compression not supported in this installation)");
                }
        }
 #endif
@@ -405,9 +400,9 @@ RestoreArchive(Archive *AHX)
         */
        if (ropt->useDB)
        {
-               ahlog(AH, 1, "connecting to database for restore\n");
+               pg_log_info("connecting to database for restore");
                if (AH->version < K_VERS_1_3)
-                       exit_horribly(modulename, "direct database connections are not supported in pre-1.3 archives\n");
+                       fatal("direct database connections are not supported in pre-1.3 archives");
 
                /*
                 * We don't want to guess at whether the dump will successfully
@@ -452,7 +447,7 @@ RestoreArchive(Archive *AHX)
                if (impliedDataOnly)
                {
                        ropt->dataOnly = impliedDataOnly;
-                       ahlog(AH, 1, "implied data-only restore\n");
+                       pg_log_info("implied data-only restore");
                }
        }
 
@@ -518,7 +513,7 @@ RestoreArchive(Archive *AHX)
                        /* Otherwise, drop anything that's selected and has a dropStmt */
                        if (((te->reqs & (REQ_SCHEMA | REQ_DATA)) != 0) && te->dropStmt)
                        {
-                               ahlog(AH, 1, "dropping %s %s\n", te->desc, te->tag);
+                               pg_log_info("dropping %s %s", te->desc, te->tag);
                                /* Select owner and schema as necessary */
                                _becomeOwner(AH, te);
                                _selectOutputSchema(AH, te->namespace);
@@ -613,8 +608,7 @@ RestoreArchive(Archive *AHX)
                                                                else
                                                                {
                                                                        /* complain and emit unmodified command */
-                                                                       write_msg(modulename,
-                                                                                         "WARNING: could not find where to insert IF EXISTS in statement \"%s\"\n",
+                                                                       pg_log_warning("could not find where to insert IF EXISTS in statement \"%s\"",
                                                                                          dropStmtOrig);
                                                                        appendPQExpBufferStr(ftStmt, dropStmt);
                                                                }
@@ -770,9 +764,9 @@ restore_toc_entry(ArchiveHandle *AH, TocEntry *te, bool is_parallel)
        if (!ropt->suppressDumpWarnings && strcmp(te->desc, "WARNING") == 0)
        {
                if (!ropt->dataOnly && te->defn != NULL && strlen(te->defn) != 0)
-                       write_msg(modulename, "warning from original dump file: %s\n", te->defn);
+                       pg_log_warning("warning from original dump file: %s", te->defn);
                else if (te->copyStmt != NULL && strlen(te->copyStmt) != 0)
-                       write_msg(modulename, "warning from original dump file: %s\n", te->copyStmt);
+                       pg_log_warning("warning from original dump file: %s", te->copyStmt);
        }
 
        /* Work out what, if anything, we want from this entry */
@@ -787,10 +781,11 @@ restore_toc_entry(ArchiveHandle *AH, TocEntry *te, bool is_parallel)
        {
                /* Show namespace in log message if available */
                if (te->namespace)
-                       ahlog(AH, 1, "creating %s \"%s.%s\"\n",
-                                 te->desc, te->namespace, te->tag);
+                       pg_log_info("creating %s \"%s.%s\"",
+                                               te->desc, te->namespace, te->tag);
                else
-                       ahlog(AH, 1, "creating %s \"%s\"\n", te->desc, te->tag);
+                       pg_log_info("creating %s \"%s\"",
+                                               te->desc, te->tag);
 
                _printTocEntry(AH, te, false);
                defnDumped = true;
@@ -846,7 +841,7 @@ restore_toc_entry(ArchiveHandle *AH, TocEntry *te, bool is_parallel)
                        appendConnStrVal(&connstr, te->tag);
                        /* Abandon struct, but keep its buffer until process exit. */
 
-                       ahlog(AH, 1, "connecting to new database \"%s\"\n", te->tag);
+                       pg_log_info("connecting to new database \"%s\"", te->tag);
                        _reconnectToDB(AH, te->tag);
                        ropt->dbname = connstr.data;
                }
@@ -874,7 +869,7 @@ restore_toc_entry(ArchiveHandle *AH, TocEntry *te, bool is_parallel)
                                if (strcmp(te->desc, "BLOBS") == 0 ||
                                        strcmp(te->desc, "BLOB COMMENTS") == 0)
                                {
-                                       ahlog(AH, 1, "processing %s\n", te->desc);
+                                       pg_log_info("processing %s", te->desc);