Here is a rolling file log handler I put together, feel free to use it. The only enhancement you may want to add is the option to delete files after x days or only have so many days of logs, and maybe choose your own format of the date. I can make a PR if you would think its useful
func RollingFile(path,filePrefix,fileSuffix string, fmtr log.Format) (log.Handler) {
handler := &RollingFileHandler{FilePrefix:filePrefix,FileSuffix:fileSuffix,Path:path,Format:fmtr}
e:= handler.Create()
if e!=nil {
panic("Unable to create logger for " + path +"/"+ filePrefix + fileSuffix)
}
return handler
}
type RollingFileHandler struct {
Stream io.WriteCloser
FormattedDay string
Handler log.Handler
Path,FilePrefix, FileSuffix string
Format log.Format
}
func (h *RollingFileHandler) Close () error {
if h.Stream!=nil {
stream := h.Stream
h.Stream=nil
return stream.Close()
}
return nil
}
func (h *RollingFileHandler) Create () error {
h.Close()
formattedDay :=h.FilePrefix + time.Now().Format("2006-01-02") + h.FileSuffix
h.FormattedDay = formattedDay
path:=filepath.Join(h.Path,h.FormattedDay)
f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return err
}
h.Stream = f
h.Handler = log.StreamHandler(h.Stream,h.Format)
return nil
}
func (h *RollingFileHandler) Log (r *log.Record) error {
// Check the current day to see if the log should be closed
formattedDay :=h.FilePrefix + time.Now().Format("2006-01-02") + h.FileSuffix
if formattedDay!=h.FormattedDay || h.Stream==nil{
err := h.Create()
if err!=nil {
return err
}
}
h.Handler.Log(r)
return nil
}
Here is a rolling file log handler I put together, feel free to use it. The only enhancement you may want to add is the option to delete files after x days or only have so many days of logs, and maybe choose your own format of the date. I can make a PR if you would think its useful