How to write log to file

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

    To help others, I create a basic log function to handle the logging in both cases, if you want the output to stdout, then turn debug on, its straight forward to do a switch flag so you can choose your output.

    func myLog(msg ...interface{}) {
        defer func() { r := recover(); if r != nil { fmt.Print("Error detected logging:", r) } }()
        if conf.DEBUG {
            fmt.Println(msg)
        } else {
            logfile, err := os.OpenFile(conf.LOGDIR+"/"+conf.AppName+".log", os.O_RDWR | os.O_CREATE | os.O_APPEND,0666)
            if !checkErr(err) {
                log.SetOutput(logfile)
                log.Println(msg)
            }
            defer logfile.Close()
        }
    }
    
    
    
    
    

提交回复
热议问题