29

在Golang中 Log 打印行号等信息 - 鸡尾酒的笔记

 4 years ago
source link: https://blog.cocktail1024.top/archives/133.html?
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

默认情况下,log 不会打印行号 和文件名,debug 的时候定位比较麻烦,

默认输出:

2019/10/14 15:10:22  要打印的日志。。。

增加文件名和行号

package main

import "log"

func main() {
    log.SetFlags(log.Lshortfile | log.LstdFlags) // set flags
    log.Println( "log 内容。。。")
}
2019/10/14 15:12:48 file.go:7: log 内容。。。

当时这样有个不足,如果有同名的文件,还是不好定位

使用完整文件名

package main

import "log"

func main() {
    log.SetFlags(log.Lshortfile | log.Llongfile) // set flags
    log.Println( "log 内容。。。")
}
2019/10/14 15:14:49 /usercode/file.go:7: log 内容。。。

log.SetFlags 常量值

const (

Ldate         = 1 << iota     // the date in the local time zone: 2009/01/23
Ltime                         // the time in the local time zone: 01:23:23
Lmicroseconds                 // microsecond resolution: 01:23:23.123123.  assumes Ltime.
Llongfile                     // full file name and line number: /a/b/c/d.go:23
Lshortfile                    // final file name element and line number: d.go:23. overrides Llongfile
LUTC                          // if Ldate or Ltime is set, use UTC rather than the local time zone
LstdFlags     = Ldate | Ltime // initial values for the standard logger

获取当前行数,文件名,函数名(方法名):

package main

import (
       "runtime"
       "fmt"
)

func main() {
        funcName, file, line, ok := runtime.Caller(0)
        if ok {
            fmt.Println("Func Name=" + runtime.FuncForPC(funcName).Name())
            fmt.Printf("file: %s    line=%d\n", file, line)
        }
}

参考:http://wendal.net/446.html


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK