NSS
NSS

Reputation: 795

How to get file and function name for loggers

I'm using logrus OS which works as expected, now we have a requirement to add to the logger output the file and the function which from where you put the logger call,

we need it to be something like

File log-ut-usage

func main(){


  logs := lts.InitLogger("test","1","debug")

  logs.Debugf("test 123")
....

}

This is the required output


{"file":"log-ut-usage/main.go:21","function":"main","level":"warn","test 123":"ddd","timestamp":"2019-10-02T09:21:39.309559Z"}

currently we got the file and function of the

file logger.go

func InitLog(label string) LoggerI {

loggerImpl = &logrus.Logger{
        Out:          os.Stdout,
        Level:        level,
        ReportCaller: true,
        Formatter: &logrus.JSONFormatter{
            TimestampFormat: timestampFormat,
            CallerPrettyfier: func(f *runtime.Frame) (string, string) {
                s := strings.Split(f.Function, ".")
                funcname := s[len(s)-1]
                _, filename := path.Split(f.File)
                return funcname, filename
            },
        },
    }

This is the (unwanted) output

{"file":"logger.go","func":"InitLog","level":"debug","msg":"test 123","time":"2019-10-02 12:21:39"}

I dont want to get the file logger.go where we coded the json formater, I want to get the file that with the usage of the logger .

Upvotes: 3

Views: 9102

Answers (2)

Azeem
Azeem

Reputation: 14677

You can wrap your logger with file, function and line information and then use that.

Here's an example (live):

package main

import (
    "os"
    "runtime"
    "strconv"
    "strings"

    log "github.com/sirupsen/logrus"
)

func init() {
    log.SetFormatter(&log.JSONFormatter{})
    log.SetOutput(os.Stdout)
}

func logger() *log.Entry {
    pc, file, line, ok := runtime.Caller(1)
    if !ok {
        panic("Could not get context info for logger!")
    }

    filename := file[strings.LastIndex(file, "/")+1:] + ":" + strconv.Itoa(line)
    funcname := runtime.FuncForPC(pc).Name()
    fn := funcname[strings.LastIndex(funcname, ".")+1:]
    return log.WithField("file", filename).WithField("function", fn)
}

func test() {
    logger().Info("Testing...")
}

func main() {
    logger().Info("Testing...")
    test()
}

Output:

{"file":"prog.go:34","function":"main","level":"info","msg":"Testing...","time":"2009-11-10T23:00:00Z"}
{"file":"prog.go:30","function":"test","level":"info","msg":"Testing...","time":"2009-11-10T23:00:00Z"}

Upvotes: 9

p1gd0g
p1gd0g

Reputation: 711

Have you tried to use debug.Stack() to fetch the file name which calls InitLog?

https://play.golang.org/p/g6yLGsiuEEn

goroutine 1 [running]:
runtime/debug.Stack(0x15d6b0, 0x3, 0x68360, 0x1580)
    /usr/local/go/src/runtime/debug/stack.go:24 +0xc0
main.fun2()
    /tmp/sandbox834348417/prog.go:20 +0x20
main.fun1(...)
    /tmp/sandbox834348417/prog.go:15
main.main()
    /tmp/sandbox834348417/prog.go:10 +0x20

Hope it works.

Upvotes: 0

Related Questions