I am using for logging in my golang scripts, however I want to get the filename and the line number which is logging the message. I am able to get that using the below code:

package main import ( "fmt" "os" "runtime" "strings" "" ) func GetLogger() (*logrus.Logger, *os.File) { log := logrus.New() log.SetReportCaller(true) file, err := os.OpenFile("info.log", os.O_CREATE|os.O_APPEND, 0644) if err != nil { log.Fatal(err) } log.Out = file log.Formatter = &logrus.TextFormatter{ CallerPrettyfier: func(f *runtime.Frame) (string, string) { repopath := fmt.Sprintf("%s/src/", os.Getenv("GOPATH")) filename := strings.Replace(f.File, repopath, "", -1) return fmt.Sprintf("%s()", f.Function), fmt.Sprintf("%s:%d", filename, f.Line) }, } return log, file } 

However this gives log in the below format:

time="2020-04-02T11:43:19+05:30" level=info msg=Hello func="main.main()" file="D:/.../main.go:13"

But I want the log in format as below:

Apr 02 00:00:00 INFO main.go:20 : Hello this is a log line

How can a custom formatter be written to get this?

5 Answers

This option is included in the library itself since the end of 2018.

Just set 'SetReportCaller' to true.

Here's an example:

package main import ( log "" ) func main() { // Add this line for logging filename and line number! log.SetReportCaller(true) log.Println("hello world") } 

The output:

INFO[0000]/home/trex/go/src/awesomeProject/main.go:11 main.main() hello world 

FYI

log.SetReportCaller(true) log.SetFormatter(&log.JSONFormatter{ CallerPrettyfier: func(frame *runtime.Frame) (function string, file string) { fileName := path.Base(frame.File) + ":" + strconv.Itoa(frame.Line) //return frame.Function, fileName return "", fileName }, }) 

output:

{"file":"inspParse.go:290","level":"info","msg":"(3, 24), ","time":"2021-08-30T16:41:38+08:00"} 
1

The package you're using produces structured log output: that is key/value pairs. It looks like you want just a plain text logger.

The standard logger import "log", produces output quite like what you want: log.New(out, "INFO", .Ldate|log.Ltime|log.Lshortfile). (See on the playground)

Here's example output:

INFO 2009/11/10 23:00:00 prog.go:10: hello 

In go1.14, the extra flag log.Lmsgprefix moves the INFO to before the message, if that's preferable (and you can wait).

If the standard library logger doesn't do what you want (and you're not prepared to live with it), why not just copy it and edit it, essentially making your own log package? It's around 400 lines of straightforward code, and by the time you remove the parts you don't want, it'll be a lot less.

The source is here:

Showing file, function name, and line number with logrus:

func Error(err error, msg ...interface{}) { if pc, file, line, ok := runtime.Caller(1); ok { file = file[strings.LastIndex(file, "/")+1:] funcName := runtime.FuncForPC(pc).Name() logrus.WithFields( logrus.Fields{ "err": err, "src": fmt.Sprintf("%s:%s:%d", file, funcName, line), }).Error(msg...) } } 

Call this in every log event.

you can take advantage of codes below

package main import ( "bytes" "fmt" "" "io" "os" "strings" ) type MyFormatter struct {} var levelList = [] string{ "PANIC", "FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE", } func (mf *MyFormatter) Format(entry *logrus.Entry) ([]byte, error){ var b *bytes.Buffer if entry.Buffer != nil { b = entry.Buffer } else { b = &bytes.Buffer{} } level := levelList[int(entry.Level)] strList := strings.Split(entry.Caller.File, "/") fileName := strList[len(strList)-1] b.WriteString(fmt.Sprintf("%s - %s - [line:%d] - %s - %s\n", entry.Time.Format("2006-01-02 15:04:05,678"), fileName, entry.Caller.Line, level, entry.Message)) return b.Bytes(), nil } func MakeLogger(filename string, display bool) *logrus.Logger { f, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644) if err != nil { panic(err.Error()) } logger := logrus.New() if display { logger.SetOutput(io.MultiWriter(os.Stdout, f)) } else { logger.SetOutput(io.MultiWriter(f)) } logger.SetReportCaller(true) logger.SetFormatter(&MyFormatter{}) return logger } func main() { logger := MakeLogger("/tmp/test.log", true) logger.Info("hello world!") } 

Result: /tmp/test.log

2021-11-24 00:49:10,678 - main.go - [line:58] - INFO - hello world!

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy