func WriteToFile()

in pkg/filter/accesslog/log.go [80:128]


func WriteToFile(accessLogMsg string, filePath string) error {
	pd := filepath.Dir(filePath)
	if _, err := os.Stat(pd); err != nil {
		if os.IsExist(err) {
			logger.Warnf("can not open log dir: %s, %v", filePath, err)
		}
		err = os.MkdirAll(pd, os.ModePerm)
		if err != nil {
			logger.Warnf("can not create log dir: %s, %v", filePath, err)
			return err
		}
	}
	logFile, err := os.OpenFile(filePath, os.O_CREATE|os.O_APPEND|os.O_RDWR, constant.LogFileMode)
	if err != nil {
		logger.Warnf("can not open the access log file: %s, %v", filePath, err)
		return err
	}
	now := time.Now().Format(constant.FileDateFormat)
	fileInfo, err := logFile.Stat()
	if err != nil {
		logger.Warnf("can not get the info of access log file: %s, %v", filePath, err)
		return err
	}
	last := fileInfo.ModTime().Format(constant.FileDateFormat)

	// this is confused.
	// for example, if the last = '2020-03-04'
	// and today is '2020-03-05'
	// we will create one new file to log access data
	// By this way, we can split the access log based on days.
	if now != last {
		err = os.Rename(fileInfo.Name(), fileInfo.Name()+"."+now)
		if err != nil {
			logger.Warnf("can not rename access log file: %s, %v", fileInfo.Name(), err)
			return err
		}
		logFile, err = os.OpenFile(fileInfo.Name(), os.O_CREATE|os.O_APPEND|os.O_RDWR, constant.LogFileMode)
		if err != nil {
			logger.Warnf("can not open access log file: %s, %v", fileInfo.Name(), err)
			return err
		}
	}
	_, err = logFile.WriteString(accessLogMsg + "\n")
	if err != nil {
		logger.Warnf("can not write to access log file: %s, v%", fileInfo.Name(), err)
		return err
	}
	return nil
}