LoginSignup
35
23

More than 5 years have passed since last update.

Go で実行中の行数、ファイル名の取得

Posted at

Go では FILELINE はありません。
これは、プリプロセッサを省いてコンパイルスピードを早めたいかららしいです。

しかし、 Go 標準の log モジュールは 以下のようにフラグでこれらを出力できます。

package main
import "log"

func main() {
  // どちらかを指定
  log.setFlags(log.Llongfile) // full file name and line number: /a/b/c/d.go:23
  log.setFlags(log.Lshortfile) // final file name element and line number: d.go:23. overrides Llongfile
  log.Println("debug log")
}

自分でちょっとした logger を組みたいときに、これらの情報をどう取得するかを知りたかったので log のソースを読んだら、 runtime モジュールを使えば良いことがわかりました。

package main

import (
  "runtime"
  "fmt"
)

func main() {
  // func Caller(skip int) (pc uintptr, file string, line int, ok bool)
  fmt.Println(runtime.Caller(1))
}

Caller の引数は、どこまでスタックを遡るかなので、メソッドを呼び出してる行や、そのメソッドを呼び出すメソッドを呼び出す行の番号など、数字を増やすと取得できます。

自前 logger を作るときとかにどうぞ。

35
23
0

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
35
23