title: Logging to a file in golang
body: <p>I am starting out with golang, and as I am starting to build out my applciation I want to add logging from the start, and that is where I am running into issues.</p>
  
  <p>If I open a file and use the standard logging library, I am able to write to a file.  Like so.</p>
  
  <pre><code>    package main
  
  
  
     import (
          "os"
          "fmt"
          "log"
      )
  
  
      func main() {
          // open a file
          f, err := os.OpenFile("test.log", os.O_APPEND | os.O_CREATE | os.O_RDWR, 0666)
          if err != nil {
              fmt.Printf("error opening file: %v", err)
          }
  
          // don't forget to close it
          defer f.Close()
  
          // assign it to the standard logger
          log.SetOutput(f)
  
          log.Output(1, "this is an event")
  
      }
  </code></pre>
  
  <p>I will get my test.log with the log line in it.  However if I try to adapt this to support logrus <a href="https://github.com/Sirupsen/logrus" rel="noreferrer">https://github.com/Sirupsen/logrus</a> like this</p>
  
  <pre><code>    package main
  
  import (
      "os"
      "fmt"
      log "github.com/Sirupsen/logrus"
  )
  
  func init() {
  
      // open a file
      f, err := os.OpenFile("testlogrus.log", os.O_APPEND | os.O_CREATE | os.O_RDWR, 0666)
      if err != nil {
          fmt.Printf("error opening file: %v", err)
      }
  
      // don't forget to close it
      defer f.Close()
  
      // Log as JSON instead of the default ASCII formatter.
      log.SetFormatter(&amp;log.JSONFormatter{})
  
      // Output to stderr instead of stdout, could also be a file.
      log.SetOutput(f)
  
      // Only log the warning severity or above.
      log.SetLevel(log.DebugLevel)
  }
  
  
  func main() {
  
      log.WithFields(log.Fields{
          "Animal": "Logrus",
      }).Info("A logrus appears")
  
  
  }
  </code></pre>
  
  <p>All I will ever see are errors.</p>
  
  <p>Failed to write to log, write testlogrus.log: bad file descriptor</p>
  
  <p>All I ever get is the bad file descriptor error.  Any ideas what I am doing wrong?</p>
  
  <p>Thanks
  Craig</p>