rs / zerolog

Zero Allocation JSON Logger
MIT License
10.41k stars 567 forks source link

Feature Request: shorter filename in output #402

Open laoshaw opened 2 years ago

laoshaw commented 2 years ago

By default zerolog outputs a full path and filename, sometimes it's just too long, can I have the filename directly instead of its full-path/filename? can I configure zerolog with some flags to do that?

laoshaw commented 2 years ago

Basically, the "Lshortfile" flag in stdlib's log package.

weisdd commented 2 years ago

@laoshaw zerolog has a global variable called CallerMarshalFunc that you can use to form whatever name you prefer:

https://github.com/rs/zerolog/blob/c0c2e11fc3cd04ae28d856789cf58ffd1666bc3f/globals.go#L63-L66

The standard implementation in Go log package looks like this (Source):

if l.flag&Lshortfile != 0 {
    short := file
    for i := len(file) - 1; i > 0; i-- {
        if file[i] == '/' {
            short = file[i+1:]
            break
        }
    }
    file = short
}

So, basically, here's the way to get something similar to "Lshortfile":

zerolog.CallerMarshalFunc = func(file string, line int) string {
    short := file
    for i := len(file) - 1; i > 0; i-- {
        if file[i] == '/' {
            short = file[i+1:]
            break
        }
    }
    file = short
    return file + ":" + strconv.Itoa(line)
}

With that variable set, a call:

zlog.Info().Caller().Msg("test")

Would produce:

{"level":"info","caller":"main.go:90","time":"2022-03-12T15:56:42+01:00","message":"test"}
laoshaw commented 2 years ago

Thanks. That shall work. Any chance if this can be added to code base.

weisdd commented 2 years ago

@laoshaw I'm just a random zerolog user, can't comment on that. :)

stefan-cross commented 1 year ago

Just to note, it looks like the CallerMarshalFunc func singature has changed but the above would still work using:

func(_ uintptr, file string, line int)