Move logrus setup code to log package

Signed-off-by: Maksym Pavlenko <pavlenko.maksym@gmail.com>
This commit is contained in:
Maksym Pavlenko
2023-04-24 10:14:13 -07:00
parent fdd1be6734
commit 370be0c18f
4 changed files with 64 additions and 41 deletions

View File

@@ -18,6 +18,7 @@ package log
import (
"context"
"fmt"
"github.com/sirupsen/logrus"
)
@@ -38,6 +39,9 @@ type (
// Fields type to pass to `WithFields`, alias from `logrus`.
Fields = logrus.Fields
// Level is a logging level
Level = logrus.Level
)
const (
@@ -50,8 +54,52 @@ const (
// JSONFormat represents the JSON logging format
JSONFormat = "json"
// TraceLevel level.
TraceLevel = logrus.TraceLevel
// DebugLevel level.
DebugLevel = logrus.DebugLevel
// InfoLevel level.
InfoLevel = logrus.InfoLevel
)
// SetLevel sets log level globally.
func SetLevel(level string) error {
lvl, err := logrus.ParseLevel(level)
if err != nil {
return err
}
logrus.SetLevel(lvl)
return nil
}
// GetLevel returns the current log level.
func GetLevel() Level {
return logrus.GetLevel()
}
// SetFormat sets log output format
func SetFormat(format string) error {
switch format {
case TextFormat:
logrus.SetFormatter(&logrus.TextFormatter{
TimestampFormat: RFC3339NanoFixed,
FullTimestamp: true,
})
case JSONFormat:
logrus.SetFormatter(&logrus.JSONFormatter{
TimestampFormat: RFC3339NanoFixed,
})
default:
return fmt.Errorf("unknown log format: %s", format)
}
return nil
}
// WithLogger returns a new context with the provided logger. Use in
// combination with logger.WithField(s) for great effect.
func WithLogger(ctx context.Context, logger *logrus.Entry) context.Context {