Inject more `CallerOffset` in `pterm.NewSlogHandler`
MarvinJWendt opened this issue · comments
As discussed in #599
The slog
handler for pterm.Logger
adds additional function calls, which break the default offset of pterm.Logger
. We could inject more offset into the passed pterm.Logger
when pterm.NewSlogHandler
is called. To make this change non-breaking, we should only inject the offset, if the passed pterm.Logger
has no manually configured offset.
/cc @ccremer
Injecting the offset is not as easy as thought initially, since the pterm.Logger
is passed as a pointer. So changing the offset in pterm.NewSlogHandler
would change the offset in the logger itself, which could be used somewhere else. Passing the logger via a pointer has the advantage, that the logger configuration can be changed on the fly, e.g.:
logger := pterm.DefaultLogger.WithCaller()
logger.Info("default logger with caller")
slogger := slog.New(pterm.NewSlogHandler(logger))
slogger.Info("slog logger with caller")
logger.Info("default logger with caller 2")
slogger.Debug("This message should not print")
logger.Level = pterm.LogLevelDebug // <-- This should still be possible
slogger.Debug("This message should print")
So we need to temporarily fork the logger in the slog
handler, when it is used.
Another benefit of this is, that we can change the offset if the slog
package is refactored. Before that change, every repo using PTerm would have to change their manual offset.