github.com/TBD54566975/ftl@v0.219.0/internal/log/api.go (about)

     1  package log
     2  
     3  import (
     4  	"context"
     5  	"os"
     6  )
     7  
     8  type Sink interface {
     9  	Log(entry Entry) error
    10  }
    11  
    12  type Interface interface {
    13  	Log(entry Entry)
    14  	Logf(level Level, format string, args ...interface{})
    15  	Tracef(format string, args ...interface{})
    16  	Debugf(format string, args ...interface{})
    17  	Infof(format string, args ...interface{})
    18  	Warnf(format string, args ...interface{})
    19  	// Errorf conditionally logs an error. If err is nil, nothing is logged.
    20  	Errorf(err error, format string, args ...interface{})
    21  }
    22  
    23  // Level is the log level.
    24  //
    25  //go:generate enumer -type=Level -text -transform=lower -output log_level_string.go
    26  type Level int
    27  
    28  // Log levels.
    29  const (
    30  	// Default is a special value that means the log level will use a default.
    31  	Default Level = 0
    32  	Trace   Level = 1
    33  	Debug   Level = 5
    34  	Info    Level = 9
    35  	Warn    Level = 13
    36  	Error   Level = 17
    37  )
    38  
    39  // Severity returns the open telemetry severity of the log level.
    40  func (l Level) Severity() int {
    41  	return int(l)
    42  }
    43  
    44  // ParseLevel parses a log level from text.
    45  func ParseLevel(input string) (Level, error) {
    46  	var level Level
    47  	err := level.UnmarshalText([]byte(input))
    48  	return level, err
    49  }
    50  
    51  type contextKey struct{}
    52  
    53  // FromContext retrieves the current logger from the context or panics
    54  func FromContext(ctx context.Context) *Logger {
    55  	logger, ok := ctx.Value(contextKey{}).(*Logger)
    56  	if ok {
    57  		return logger
    58  	}
    59  	panic("no logger in context")
    60  }
    61  
    62  // ContextWithLogger returns a new context with the given logger attached. Use
    63  // FromContext to retrieve it.
    64  func ContextWithLogger(ctx context.Context, logger *Logger) context.Context {
    65  	return context.WithValue(ctx, contextKey{}, logger)
    66  }
    67  
    68  func ContextWithNewDefaultLogger(ctx context.Context) context.Context {
    69  	// Matches LOG_COLOR in log.Config. This is a special case for the default logger in testing.
    70  	color := os.Getenv("LOG_COLOR") != ""
    71  	return ContextWithLogger(ctx, Configure(os.Stderr, Config{Level: Debug, Color: color}))
    72  }