How to write log to file

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

    I'm writing logs to the files, which are generate on daily basis (per day one log file is getting generated). This approach is working fine for me :

    var (
        serverLogger *log.Logger
    )
    
    func init() {
        // set location of log file
        date := time.Now().Format("2006-01-02")
        var logpath = os.Getenv(constant.XDirectoryPath) + constant.LogFilePath + date + constant.LogFileExtension
        os.MkdirAll(os.Getenv(constant.XDirectoryPath)+constant.LogFilePath, os.ModePerm)
        flag.Parse()
        var file, err1 = os.OpenFile(logpath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
    
        if err1 != nil {
            panic(err1)
        }
        mw := io.MultiWriter(os.Stdout, file)
        serverLogger = log.New(mw, constant.Empty, log.LstdFlags)
        serverLogger.Println("LogFile : " + logpath)
    }
    
    // LogServer logs to server's log file
    func LogServer(logLevel enum.LogLevel, message string) {
        _, file, no, ok := runtime.Caller(1)
        logLineData := "logger_server.go"
        if ok {
            file = shortenFilePath(file)
            logLineData = fmt.Sprintf(file + constant.ColonWithSpace + strconv.Itoa(no) + constant.HyphenWithSpace)
        }
        serverLogger.Println(logLineData + logLevel.String() + constant.HyphenWithSpace + message)
    }
    
    // ShortenFilePath Shortens file path to a/b/c/d.go tp d.go
    func shortenFilePath(file string) string {
        short := file
        for i := len(file) - 1; i > 0; i-- {
            if file[i] == constant.ForwardSlash {
                short = file[i+1:]
                break
            }
        }
        file = short
        return file
    }
    

    "shortenFilePath()" method used to get the name of the file from full path of file. and "LogServer()" method is used to create a formatted log statement (contains : filename, line number, log level, error statement etc...)

提交回复
热议问题