log: add log.Entry type

Don't return logrus types from exported functions.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
Sebastiaan van Stijn 2023-07-30 21:18:16 +02:00
parent dd67240f1b
commit 634a4a1bbf
No known key found for this signature in database
GPG Key ID: 76698F39D527CE8C

View File

@ -31,6 +31,14 @@ type loggerKey struct{}
// Fields type to pass to "WithFields". // Fields type to pass to "WithFields".
type Fields = logrus.Fields type Fields = logrus.Fields
// Entry is a logging entry. It contains all the fields passed with
// [Entry.WithFields]. It's finally logged when Trace, Debug, Info, Warn,
// Error, Fatal or Panic is called on it. These objects can be reused and
// passed around as much as you wish to avoid field duplication.
//
// Entry is a transitional type, and currently an alias for [logrus.Entry].
type Entry = logrus.Entry
// RFC3339NanoFixed is [time.RFC3339Nano] with nanoseconds padded using // RFC3339NanoFixed is [time.RFC3339Nano] with nanoseconds padded using
// zeros to ensure the formatted time is always the same number of // zeros to ensure the formatted time is always the same number of
// characters. // characters.
@ -129,20 +137,20 @@ func SetFormat(format OutputFormat) error {
// WithLogger returns a new context with the provided logger. Use in // WithLogger returns a new context with the provided logger. Use in
// combination with logger.WithField(s) for great effect. // combination with logger.WithField(s) for great effect.
func WithLogger(ctx context.Context, logger *logrus.Entry) context.Context { func WithLogger(ctx context.Context, logger *Entry) context.Context {
return context.WithValue(ctx, loggerKey{}, logger.WithContext(ctx)) return context.WithValue(ctx, loggerKey{}, logger.WithContext(ctx))
} }
// GetLogger retrieves the current logger from the context. If no logger is // GetLogger retrieves the current logger from the context. If no logger is
// available, the default logger is returned. // available, the default logger is returned.
func GetLogger(ctx context.Context) *logrus.Entry { func GetLogger(ctx context.Context) *Entry {
return G(ctx) return G(ctx)
} }
// G is a shorthand for [GetLogger]. // G is a shorthand for [GetLogger].
func G(ctx context.Context) *logrus.Entry { func G(ctx context.Context) *Entry {
if logger := ctx.Value(loggerKey{}); logger != nil { if logger := ctx.Value(loggerKey{}); logger != nil {
return logger.(*logrus.Entry) return logger.(*Entry)
} }
return L.WithContext(ctx) return L.WithContext(ctx)
} }