iris icon indicating copy to clipboard operation
iris copied to clipboard

AccessLog can not flush into file until I stop the app

Open qiuhongshuai opened this issue 1 year ago • 2 comments

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.

qiuhongshuai avatar Apr 10 '23 12:04 qiuhongshuai

@kataras +1

danlanxiaohei avatar Apr 12 '23 06:04 danlanxiaohei

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:

  1. You can use the accesslog.FileUnbuffered(path string) or pass the os.Open file result of your filepath to accesslog.New function, this will flush the contents on every request but will reduce performance between parallel requests as you may guess.

  2. The AccessLog instance has the Flush 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.

kataras avatar Apr 12 '23 11:04 kataras