La Vita è Bella


Force rotating glog in Go

If you use glog package in Go as your logger, one thing you'll notice is that the only way it rotates is by size. There's MaxSize defined and exported, and glog will rotate the log file when the current file exceeding it (1,800 MiB). There's no way to rotate by time, and there's no way to do manually log rotating.

Actually that's not true. There's a trick.

Did you notice that I emphasized the word "exported" when describing MaxSize? That's how we could implement manual log rotating.

Here is an example:

// RotateGlogInfo rotates glog info log
func RotateGlogInfo(message string, size uint64) {
  prevMaxSize := glog.MaxSize
  glog.MaxSize = size
  glog.MaxSize = prevMaxSize

The idea is simple: we change glog.MaxSize to a very small value, so that the next write will definitely makes it to rotate. After that, we just restore the default size value.

The key here is the size value passed in. This must be small enough to ensure that rotate happens, but it cannot be too small (e.g. 0 or 1), otherwise if another thread writes a log larger than size before we restore the old value, that log alone will occupy a single log file (we certainly do not want a lock to block all other logging threads while rotating). If you write logs often, a value like 1024 should work fine enough for you.

19:10:05 by fishy - Permanent Link

May the Force be with you. RAmen