diff --git a/ocis-pkg/log/log.go b/ocis-pkg/log/log.go index b217c77891..fda1fa050e 100644 --- a/ocis-pkg/log/log.go +++ b/ocis-pkg/log/log.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "os" + "runtime" "strings" "time" @@ -64,6 +65,18 @@ func NopLogger() Logger { return Logger{zerolog.Nop()} } +type LineInfoHook struct{} + +// Run is a hook to add line info to log messages. +// I found the zerolog example for this here: +// https://github.com/rs/zerolog/issues/22#issuecomment-1127295489 +func (h LineInfoHook) Run(e *zerolog.Event, l zerolog.Level, msg string) { + _, file, line, ok := runtime.Caller(3) + if ok { + e.Str("line", fmt.Sprintf("%s:%d", file, line)) + } +} + // NewLogger initializes a new logger instance. func NewLogger(opts ...Option) Logger { options := newOptions(opts...) @@ -119,6 +132,11 @@ func NewLogger(opts ...Option) Logger { Timestamp(). Logger().Level(logLevel) + if logLevel <= zerolog.InfoLevel { + var lineInfoHook LineInfoHook + logger = logger.Hook(lineInfoHook) + } + return Logger{ logger, }