gitlab.com/gitlab-org/labkit@v1.21.0/log/logger.go (about) 1 package log 2 3 import ( 4 "context" 5 "os" 6 7 "github.com/sirupsen/logrus" 8 "gitlab.com/gitlab-org/labkit/correlation" 9 ) 10 11 var logger = logrus.StandardLogger() 12 13 func init() { //nolint:gochecknoinits 14 // Enfore our own defaults on the logrus stdlogger 15 logger.Out = os.Stderr 16 logger.Formatter = &logrus.TextFormatter{} 17 logger.Level = logrus.InfoLevel 18 } 19 20 // ContextLogger will set the correlation id in the logger based on the context. 21 // This reference should not be held outside of the scope of the context. 22 func ContextLogger(ctx context.Context) *logrus.Entry { 23 return logger.WithFields(ContextFields(ctx)) 24 } 25 26 // WithContextFields is a utility method for logging with context and fields. 27 func WithContextFields(ctx context.Context, fields Fields) *logrus.Entry { 28 return logger.WithFields(ContextFields(ctx)).WithFields(fields) 29 } 30 31 // ContextFields a logrus fields structure with the CorrelationID set. 32 func ContextFields(ctx context.Context) Fields { 33 correlationID := correlation.ExtractFromContext(ctx) 34 35 return logrus.Fields{correlation.FieldName: correlationID} 36 }