How to write log to file

后端 未结 11 1306
抹茶落季
抹茶落季 2020-12-07 08:06

I\'m trying to write to a log file with Go.

I have tried several approaches, all of which have failed. This is what I have tried:

func TestLogging(t          


        
11条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-07 08:45

    os.Open() must have worked differently in the past, but this works for me:

    f, err := os.OpenFile("testlogfile", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
    if err != nil {
        log.Fatalf("error opening file: %v", err)
    }
    defer f.Close()
    
    log.SetOutput(f)
    log.Println("This is a test log entry")
    

    Based on the Go docs, os.Open() can't work for log.SetOutput, because it opens the file "for reading:"

    func Open

    func Open(name string) (file *File, err error) Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError.

    EDIT

    Moved defer f.Close() to after if err != nil check

提交回复
热议问题