github.com/hairyhenderson/gomplate/v4@v4.0.0-pre-2.0.20240520121557-362f058f0c93/internal/cmd/logger.go (about)

     1  package cmd
     2  
     3  import (
     4  	"io"
     5  	"log/slog"
     6  	"os"
     7  	"runtime"
     8  
     9  	"github.com/hairyhenderson/gomplate/v4/env"
    10  	"github.com/lmittmann/tint"
    11  	"golang.org/x/term"
    12  )
    13  
    14  func logFormat(out io.Writer) string {
    15  	defaultFormat := "json"
    16  	if f, ok := out.(*os.File); ok && term.IsTerminal(int(f.Fd())) {
    17  		defaultFormat = "console"
    18  	}
    19  	return env.Getenv("GOMPLATE_LOG_FORMAT", defaultFormat)
    20  }
    21  
    22  func createLogHandler(format string, out io.Writer, level slog.Level) slog.Handler {
    23  	opts := &slog.HandlerOptions{Level: level}
    24  
    25  	var handler slog.Handler
    26  	switch format {
    27  	case "console":
    28  		// logFormat() already checks if this is a terminal, but we need to
    29  		// check again because the format may be overridden with `GOMPLATE_LOG_FORMAT`
    30  		useColour := false
    31  		if f, ok := out.(*os.File); ok && term.IsTerminal(int(f.Fd())) && runtime.GOOS != "windows" {
    32  			useColour = true
    33  		}
    34  		handler = tint.NewHandler(out, &tint.Options{
    35  			Level:      level,
    36  			TimeFormat: "15:04:05",
    37  			NoColor:    !useColour,
    38  		})
    39  	case "simple":
    40  		handler = tint.NewHandler(out, &tint.Options{
    41  			Level:   level,
    42  			NoColor: true,
    43  			ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
    44  				if attr.Key == "level" {
    45  					attr.Value = slog.StringValue("")
    46  				}
    47  				if attr.Key == "time" {
    48  					attr.Value = slog.StringValue("")
    49  				}
    50  				return attr
    51  			},
    52  		})
    53  	case "logfmt":
    54  		handler = slog.NewTextHandler(out, opts)
    55  	default:
    56  		// json is still default
    57  		handler = slog.NewJSONHandler(out, opts)
    58  	}
    59  
    60  	return handler
    61  }
    62  
    63  func initLogger(out io.Writer, level slog.Level) {
    64  	// default to warn level
    65  	if level == 0 {
    66  		level = slog.LevelWarn
    67  	}
    68  
    69  	handler := createLogHandler(logFormat(out), out, level)
    70  	slog.SetDefault(slog.New(handler))
    71  }