github.com/msales/pkg/v3@v3.24.0/log/logger.go (about)

     1  package log
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"io"
     7  	"os"
     8  )
     9  
    10  type key int
    11  
    12  const (
    13  	ctxKey key = iota
    14  )
    15  
    16  var (
    17  	// Null is the null Logger instance.
    18  	Null = &nullLogger{}
    19  )
    20  
    21  // Logger represents an abstract logging object.
    22  type Logger interface {
    23  	// Debug logs a debug message.
    24  	Debug(msg string, ctx ...interface{})
    25  	// Info logs an informational message.
    26  	Info(msg string, ctx ...interface{})
    27  	// Error logs an error message.
    28  	Error(msg string, ctx ...interface{})
    29  }
    30  
    31  // WithLogger sets Logger in the context.
    32  func WithLogger(ctx context.Context, logger Logger) context.Context {
    33  	if logger == nil {
    34  		logger = Null
    35  	}
    36  	return context.WithValue(ctx, ctxKey, logger)
    37  }
    38  
    39  // FromContext returns the instance Logger in the context.
    40  func FromContext(ctx context.Context) (Logger, bool) {
    41  	stats, ok := ctx.Value(ctxKey).(Logger)
    42  	return stats, ok
    43  }
    44  
    45  // Debug logs a debug message.
    46  func Debug(ctx context.Context, msg string, pairs ...interface{}) {
    47  	withLogger(ctx, func(l Logger) {
    48  		l.Debug(msg, pairs...)
    49  	})
    50  }
    51  
    52  // Info logs an informational message.
    53  func Info(ctx context.Context, msg string, pairs ...interface{}) {
    54  	withLogger(ctx, func(l Logger) {
    55  		l.Info(msg, pairs...)
    56  	})
    57  }
    58  
    59  // Error logs an error message.
    60  func Error(ctx context.Context, msg string, pairs ...interface{}) {
    61  	withLogger(ctx, func(l Logger) {
    62  		l.Error(msg, pairs...)
    63  	})
    64  }
    65  
    66  // Fatal is equivalent to Error() followed by a call to os.Exit(1).
    67  func Fatal(ctx context.Context, msg interface{}, pairs ...interface{}) {
    68  	withLogger(ctx, func(l Logger) {
    69  		l.Error(fmt.Sprintf("%+v", msg), pairs...)
    70  
    71  		if cl, ok := l.(io.Closer); ok {
    72  			cl.Close()
    73  		}
    74  	})
    75  
    76  	os.Exit(1)
    77  }
    78  
    79  func withLogger(ctx context.Context, fn func(l Logger)) {
    80  	if l, ok := FromContext(ctx); ok {
    81  		fn(l)
    82  	} else {
    83  		fn(Null)
    84  	}
    85  }
    86  
    87  type nullLogger struct{}
    88  
    89  // Debug logs a debug message.
    90  func (l nullLogger) Debug(msg string, ctx ...interface{}) {}
    91  
    92  // Info logs an informational message.
    93  func (l nullLogger) Info(msg string, ctx ...interface{}) {}
    94  
    95  // Error logs an error message.
    96  func (l nullLogger) Error(msg string, ctx ...interface{}) {}