Go6

go runtime caller get file name and line

This project is maintained by wangfakang

golang 记录文件函数调用处文件名以及行数

一般我们的项目中的log都会记载一个函数的调用处的文件名以及调用函数所处文件饿行数,这样在追查问题饿时候可以很快.

嘿嘿,今天平安夜 (@)快乐~~ 我就直接上代码了:

/home/fakang/worker/go/demo.go

package main

import (
    "fmt"
    "runtime"
    "path"
    "strings"
)

func main() {

    _, fulleFileName, line, _ := runtime.Caller(0) //获取文件名(包括当前的路径)
    fmt.Println(fulleFileName)
    fmt.Println(line)
    var filenameend string
    filenameend = path.Base(fulleFileName) //只要文件名,去处前面饿路径
    fmt.Println("file name end=", filenameend)
    var filesufix string
    filesufix = path.Ext(filenameend) //获取文件名饿后缀 
    fmt.Println("file fix end=", filesufix)

    var filenameOnly string
    filenameOnly = strings.TrimSuffix(filenameend, filesufix) //只要文件名本身,不要文件名后缀
    fmt.Println("filenameOnly=", filenameOnly)
}

output:

/home/fakang/worker/go/demo.go
12
file name end=demo.go
file fix end=.go
filenameOnly=demo

func Base(path string) string

   Base returns the last element of path. Trailing slashes are removed before extracting the last element. 
   If the path is empty, Base returns ".". If the path consists entirely of slashes, Base returns "/". 

Communite

在使用中有任何问题,欢迎反馈给我,可以用以下联系方式跟我交流

Thx

Author