La Vita è Bella

Tuesday, July 18, 2017

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 - dev - Permanent Link

Revision: 1.2/1.2, last modified on 2017-07-29 @ 09:10.

Karma: 5 (100.00% out of 5 were positive) [+/-]

You can subscribe to RSS 2.0 feed for comments and trackbacks

There are currently no trackbacks for this item.
Use this TrackBack url to ping this item (right-click, copy link target). If your blog does not support Trackbacks you can manually add your trackback by using this form.

No comments yet

Add Comment


May the Force be with you. RAmen