Skip to content
Dhwaneet Bhatt

Time based log file rotation with zap

go, logging1 min read

zap is one of the nicely maintained, well-written and nicely performing open source logging libraries in Go. Unfortunately, not all apps in our organization are 12-factor apps and thus we still log to physical files. So, I needed a way to rotate log files while using zap. I come from Java background, and log4j has a very vast array of log rotation options. But I found it lacking in zap, clearly because in the world of containers, logging to stdout (treating logs as event streams - 12-factor logs) is very common.

To be specific, I was looking to do time based rotation (one log file per hour, helps in debugging) and not size based. On zap's FAQ, they've shown integration with lumberjack, which only supports size based rotation.

I found another library file-rotatelogs which does support time based rotation. So I used it along with zap.

The good thing about zap is that it takes any io.Writer interface as a WriteSyncer and file-rotatelogs returns *RotateLogs which implements the io.Writer interface.

Here the rotatelogs.WithRotationTime(time.Hour)) indicates hourly rotation. rotatelogs.WithMaxAge(60*24*time.Hour) indicates the files are cleaned up after 60 days.

1package main
3import (
4 "encoding/json"
5 "time"
7 rotatelogs ""
8 ""
9 ""
12func main() {
13 // initialize the rotator
14 logFile := "/var/log/app-%Y-%m-%d-%H.log"
15 rotator, err := rotatelogs.New(
16 logFile,
17 rotatelogs.WithMaxAge(60*24*time.Hour),
18 rotatelogs.WithRotationTime(time.Hour))
19 if err != nil {
20 panic(err)
21 }
23 // initialize the JSON encoding config
24 encoderConfig := map[string]string{
25 "levelEncoder": "capital",
26 "timeKey": "date",
27 "timeEncoder": "iso8601",
28 }
29 data, _ := json.Marshal(encoderConfig)
30 var encCfg zapcore.EncoderConfig
31 if err := json.Unmarshal(data, &encCfg); err != nil {
32 panic(err)
33 }
35 // add the encoder config and rotator to create a new zap logger
36 w := zapcore.AddSync(rotator)
37 core := zapcore.NewCore(
38 zapcore.NewJSONEncoder(encCfg),
39 w,
40 zap.InfoLevel)
41 logger := zap.New(core)
43 logger.Info("Now logging in a rotated file")

This will create the file /var/log/app-2020-05-18-15.log, which is exactly how we wanted it. It will automatically start logging to the next file during the start of the next hour.