title: How do I track transactions in PostgreSQL log?
body: <p>I recently inherited an application that uses PostgreSQL and I have been troubleshooting issues relating to saving records in the database.</p>
  
  <p>I know that PostgreSQL allows me to record the transaction ID in the log by including the special value of <code>%x</code> in the <code>log_line_prefix</code>. What I noticed, however, is that the first statement that occurs within a transaction always gets logged with a zero.</p>
  
  <p>If I perform the following operations in psql,</p>
  
  <pre><code>begin;
  insert into numbers (1);
  insert into numbers (2);
  commit;
  </code></pre>
  
  <p>the query log will contain the following entries:</p>
  
  <pre><code>2016-09-20 03:07:40 UTC 0 LOG:  statement: begin;
  2016-09-20 03:07:53 UTC 0 LOG:  statement: insert into numbers values (1);
  2016-09-20 03:07:58 UTC 689 LOG:  statement: insert into numbers values (2);
  2016-09-20 03:08:03 UTC 689 LOG:  statement: commit;
  </code></pre>
  
  <p>My log format is <code>%t %x</code> and as you can see, the transaction ID for the first insert statement is 0, but it changes to 689 when I execute the second insert.</p>
  
  <p>Can anyone explain why after starting a transaction PostgreSQL doesn't log the right transaction ID on the first statement? Or if I'm just doing this wrong, is there a more reliable way of identifying which queries were part of a single transaction by looking at the log file?</p>