3

I am using logrus package for logging. Want to rotate the logs on daily basis.

I have explored options like lumberjack and logrotate(8)

But lumberjack provides log rotation based on the size of the log file. Not sure if there is any way to make it rotate logs on daily basis.

For logrotate, I will have to create a separate config at the system level which I want to avoid as will have to look after two different things and scalability will an issue. Not sure how we can use this just by creating config at the project level or some other better approach.

So is there any way to do log rotating on a daily basis in Golang?

Sumit Bopche
  • 658
  • 5
  • 9

1 Answers1

2

You can try kjk/dailyrotate from Krzysztof Kowalczyk, presented in "What is dailyrotate?"

dailyrotate is a Go library that makes it easy to implement log rotation.
By defaultd logs rotate daily, at midnight UTC time.

var (
    logFile *dailyrotate.File
)

func openLogFile(pathFormat string, onClose func(string, bool)) error {
    w, err := dailyrotate.NewFile(pathFormat, onLogClose)
    if err != nil {
        return err
    }
    logFile = w
    return nil
}

func main() {
    logDir := "logs"

    // we have to ensure the directory we want to write to
    // already exists
    err := os.MkdirAll(logDir, 0755)
    if err != nil {
        log.Fatalf("os.MkdirAll()(")
    }

    pathFormat := filepath.Join(logDir, "2006-01-02.txt")
    err = openLogFile(pathFormat, onLogClose)
    if err != nil {
        log.Fatalf("openLogFile failed with '%s'\n", err)
    }

  // ... the rest of your program
}
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250