iris
iris copied to clipboard
AccessLog can not flush into file until I stop the app
The configure the accesslog as follow:
func MakeAccessLog(path string) *accesslog.AccessLog { pathToAccessLog := "./access_log.%Y%m%d" w, err := rotatelogs.New( pathToAccessLog, rotatelogs.WithMaxAge(24*time.Hour), rotatelogs.WithRotationTime(time.Hour)) if err != nil { panic(err) } ac := accesslog.New(bufio.NewWriter(w)) ac.AddOutput(os.Stdout) ac.Delim = '-' ac.TimeFormat = "2006-01-02 15:04:05" ac.Async = true ac.IP = true ac.BytesReceivedBody = true ac.BytesSentBody = true ac.BytesSent = false ac.BytesReceived = false ac.BodyMinify = true ac.RequestBody = false ac.ResponseBody = false ac.KeepMultiLineError = true ac.PanicLog = accesslog.LogHandler ac.SetFormatter(&accesslog.JSON{ HumanTime: true, }) return ac } //use it in my app ac := common.MakeAccessLog("./access.log") defer ac.Close() app.UseRouter(ac.Handler)
when I access the app, the standout ouput the accesslog normally,but the log file didn't create at the app start,but when I stopped the app ,the file and the log reocord appeared.
@kataras +1
Hello @qiuhongshuai,
You are using bufio.NewWriter
and that's why it waits for buffer to fill and then it flushes the contents to the file.
When you are using file with bufferred writer:
The file is created but, while the server is running, the contents are flushed every time the data to write is large enough and it flushes any remaining data on server shutdown.
Solutions:
-
You can use the
accesslog.FileUnbuffered(path string)
or pass theos.Open
file result of your filepath toaccesslog.New
function, this will flush the contents on every request but will reduce performance between parallel requests as you may guess. -
The
AccessLog
instance has theFlush
method, you can add a timer loop to flush the contents every 10 seconds for example.
Please respond back if you have any further questions.