From cca0c8d44d6d0860df6dca28bae2fedd3549dad0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Sw=C3=A4rd?= Date: Thu, 26 Jan 2023 11:26:50 +0100 Subject: [PATCH] Add line number and file to log messages when at debug level. --- ocis-pkg/log/log.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/ocis-pkg/log/log.go b/ocis-pkg/log/log.go index b217c7789..46cdfeb36 100644 --- a/ocis-pkg/log/log.go +++ b/ocis-pkg/log/log.go @@ -4,6 +4,8 @@ import ( "context" "fmt" "os" + "regexp" + "runtime" "strings" "time" @@ -17,6 +19,10 @@ import ( var ( RequestIDString = "request-id" + + // Match all paths outside of ocis. Will break if path does not include '/ocis/', + // but this is intended for debugging purposes. + pathRegex = regexp.MustCompile(`.*/ocis/`) ) func init() { @@ -64,6 +70,19 @@ 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 { + file := pathRegex.ReplaceAllString(file, "") + 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 +138,11 @@ func NewLogger(opts ...Option) Logger { Timestamp(). Logger().Level(logLevel) + if logLevel == zerolog.DebugLevel { + var lineInfoHook LineInfoHook + logger = logger.Hook(lineInfoHook) + } + return Logger{ logger, }