How to write log to file

后端 未结 11 1302
抹茶落季
抹茶落季 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:46

    Building on Allison and Deepak's answer, I started using logrus and really like it:

    var log = logrus.New()
    
    func init() {
    
        // log to console and file
        f, err := os.OpenFile("crawler.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
        if err != nil {
            log.Fatalf("error opening file: %v", err)
        }
        wrt := io.MultiWriter(os.Stdout, f)
    
        log.SetOutput(wrt)
    }
    

    I have a defer f.Close() in the main function

提交回复
热议问题