记录到golang中的文件

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.

If I open a file and use the standard logging library, I am able to write to a file. Like so.

    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")

    }

I will get my test.log with the log line in it. However if I try to adapt this to support logrus https://github.com/Sirupsen/logrus like this

    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(&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")


}

All I will ever see are errors.

Failed to write to log, write testlogrus.log: bad file descriptor

All I ever get is the bad file descriptor error. Any ideas what I am doing wrong?

Thanks Craig

Since you setup the file in the init function and you have defer f.Close(), the file gets closed after init returns.

you either have to keep the file open or move the whole thing into main.

On Linux In development you can write to stdout and pipe to a file. In production write to syslog. Both ways you dont need to handle the file yourself.