zerolog icon indicating copy to clipboard operation
zerolog copied to clipboard

Caller outputs different path on Windows and Linux

Open levanidev opened this issue 4 years ago • 4 comments

If we initialize logger the following way:

func newLogger() zerolog.Logger {

	return zerolog.New(zerolog.ConsoleWriter{
		Out:        os.Stderr,
		NoColor:    true,
		TimeFormat: time.StampMicro,
		PartsOrder: []string{
			zerolog.TimestampFieldName,
			zerolog.LevelFieldName,
			zerolog.CallerFieldName,
			zerolog.MessageFieldName,
		},
	}).With().Timestamp().Caller().Logger()

}

and use the returned logger:

myLog := newLogger()
myLog.Info().Msg("hello")

on windows we will get something like this

Jun 15 13:35:34.000000 INF log\log.go:21 > hello

but on linux we get:

Jun 15 13:35:34.000000 INF C:/Users/path/to/log/log.go:21 > hello

to compile for linux I used:

env GOOS=linux GOARCH=amd64 go build -o mycli

I am on Windows when compiling to Linux target.

However if I build From Linux it works as expected.

levanidev avatar Jun 15 '21 18:06 levanidev

Did you find a solution? We have the same problem here. We are building it on a MacOS.

  • If run on the Mac, the paths are shown as relative paths, like expected (app/app.go:34)
  • if run on a Windows, the paths are full paths, but the paths from the build server (/home/jenkins/workspace/jobs/our_project/app/app.go:34)

Pe-te avatar Jan 25 '22 16:01 Pe-te

Did you find a solution? We have the same problem here. We are building it on a MacOS.

* If run on the Mac, the paths are shown as relative paths, like expected (app/app.go:34)

* if run on a Windows, the paths are full paths, but the paths from the build server (/home/jenkins/workspace/jobs/our_project/app/app.go:34)

unfortunately no, i just omit the Caller() field. However there is a global CallerMarshalFunc in globals.go which you can modify to define your own marshaller func,

func(file string, line int) string {
    return file + ":" + strconv.Itoa(line)
}

I'll do some more diggin later. let me know if you figure it out

levanidev avatar Jan 25 '22 16:01 levanidev

It actually might be due to runtime.Caller() that returns fullpath on windows and only project file on linux. not 100% sure though

levanidev avatar Jan 25 '22 16:01 levanidev

Thank you for the research!

There's probably a cleaner way, but for now I got it "working" with this marshal function:

func ConfigureCallerMarshalFunc() {
	zerolog.CallerMarshalFunc = func(file string, line int) string {
		r, _ := regexp.Compile("[^\\\\/]+[\\\\/][^\\\\/]+$")
		shortPath := r.FindString(file)
		if shortPath != "" {
			file = shortPath
		}
		file = strings.ReplaceAll(file, "\\", "/")
		return file + ":" + strconv.Itoa(line)
	}
}

Pe-te avatar Jan 26 '22 13:01 Pe-te