title: How to test Go function containing log.Fatal()
body: <p>Say, I had the following code that prints some log messages. How would I go about testing that the correct messages have been logged? As <code>log.Fatal</code> calls <code>os.Exit(1)</code> the tests fail.</p>
  
  <pre><code>package main
  
  import (
      "log"
  )
  
  func hello() {
      log.Print("Hello!")
  }
  
  func goodbye() {
      log.Fatal("Goodbye!")
  }
  
  func init() {
      log.SetFlags(0)
  }
  
  func main() {
      hello()
      goodbye()
  }
  </code></pre>
  
  <p>Here are the hypothetical tests:</p>
  
  <pre><code>package main
  
  import (
      "bytes"
      "log"
      "testing"
  )
  
  
  func TestHello(t *testing.T) {
      var buf bytes.Buffer
      log.SetOutput(&amp;buf)
  
      hello()
  
      wantMsg := "Hello!\n"
      msg := buf.String()
      if msg != wantMsg {
          t.Errorf("%#v, wanted %#v", msg, wantMsg)
      }
  }
  
  func TestGoodby(t *testing.T) {
      var buf bytes.Buffer
      log.SetOutput(&amp;buf)
  
      goodbye()
  
      wantMsg := "Goodbye!\n"
      msg := buf.String()
      if msg != wantMsg {
          t.Errorf("%#v, wanted %#v", msg, wantMsg)
      }
  }
  </code></pre>