7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Golangでlogのタイムスタンプをマイクロ秒単位にする方法

Last updated at Posted at 2018-01-22

#最初に結論

logのタイムスタンプをマイクロ秒単位にするには、log.SetFlags(log.Lmicroseconds) を実行しておけばよい。
https://golang.org/pkg/log/#pkg-constants

#例

デフォルトのlog

package main

import (
	"log"
	"time"
)

func main() {
	count := 0
	for {
		time.Sleep(100 * time.Millisecond)
		log.Printf("count=%d\n", count)
		count++
	}
}
$ go run a1.go
2018/01/22 10:58:34 count=0
2018/01/22 10:58:34 count=1
2018/01/22 10:58:34 count=2
2018/01/22 10:58:34 count=3
2018/01/22 10:58:34 count=4
2018/01/22 10:58:34 count=5
2018/01/22 10:58:34 count=6
2018/01/22 10:58:34 count=7
2018/01/22 10:58:35 count=8
2018/01/22 10:58:35 count=9
2018/01/22 10:58:35 count=10
2018/01/22 10:58:35 count=11
2018/01/22 10:58:35 count=12
2018/01/22 10:58:35 count=13
2018/01/22 10:58:35 count=14

log.SetFlags(log.Lmicroseconds)した場合

package main

import (
	"log"
	"time"
)

func main() {
	log.SetFlags(log.Lmicroseconds) // <-- これを追加
	count := 0
	for {
		time.Sleep(100 * time.Millisecond)
		log.Printf("count=%d\n", count)
		count++
	}
}
$ go run a2.go
10:59:40.963792 count=0
10:59:41.064928 count=1
10:59:41.166225 count=2
10:59:41.267365 count=3
10:59:41.367690 count=4
10:59:41.468041 count=5
10:59:41.569157 count=6
10:59:41.670192 count=7
10:59:41.771581 count=8
10:59:41.871852 count=9
10:59:41.972876 count=10
10:59:42.074049 count=11
10:59:42.174963 count=12
7
6
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?