6
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

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

最初に結論

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
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
6
Help us understand the problem. What are the problem?