Below code for rotation logs:
package main
import (
"os"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
lumberjack "gopkg.in/natefinch/lumberjack.v2"
)
func main() {
logPath, _ := os.Getwd()
log := NewLoggerFp(logPath, 1, 2, 2)
log.Infof("sjkshfjsdf\n")
log.Infof("sjkshfjsdf\n")
log.Infof("sjkshfjsdf\n")
}
func NewLoggerFp(logPath string, maxSize, maxBackUp, maxAge int) *zap.SugaredLogger {
w := zapcore.AddSync(&lumberjack.Logger{
Filename: logPath "/dump.log",
MaxSize: maxSize, // megabytes
MaxBackups: maxBackUp,
MaxAge: maxAge, // days
})
core := zapcore.NewCore(
zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()),
w,
zap.InfoLevel,
)
return zap.New(core).Sugar()
}
Logs get created
How to add timestamp to dump.log
?
CodePudding user response:
I try to understand what Christian suggests. Maybe you can try this.
w := zapcore.AddSync(&lumberjack.Logger{
Filename: logPath fmt.Sprintf("/dump-%v.log", time.Now().Format(time.RFC822)),
MaxSize: maxSize, // megabytes
MaxBackups: maxBackUp,
MaxAge: maxAge, // days
})
CodePudding user response:
Have you tested it with a smaller MaxSize (or MaxAge) parameter?
According to https://pkg.go.dev/gopkg.in/natefinch/lumberjack.v2#example-Logger.Rotate, Lumberjack will append to the first file if the file exists and is less than MaxSize megabytes. When this limit is reached, timestamps are automatically added:
Whenever a write would cause the current log file exceed MaxSize megabytes, the current file is closed, renamed, and a new log file created with the original name.
Backups use the log file name given to Logger, in the form
name-timestamp.ext
where name is the filename without the extension, timestamp is the time at which the log was rotated formatted with the time.Time format of2006-01-02T15-04-05.000
and the extension is the original extension.For example, if your Logger.Filename is
/var/log/foo/server.log
, a backup created at 6:30pm on Nov 11 2016 would use the filename/var/log/foo/server-2016-11-04T18-30-00.000.log
If the file exists and its size is >= MaxSize megabytes, the file is renamed by putting the current time in a timestamp in the name immediately before the file's extension (or the end of the filename if there's no extension). A new log file is then created using original filename.
There is an open pull request to be able to customize the time stamp format: https://github.com/natefinch/lumberjack/pull/118