github.com/turbot/steampipe@v1.7.0-rc.0.0.20240517123944-7cef272d4458/pkg/dashboard/dashboardserver/output.go (about)

     1  package dashboardserver
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"io"
     7  	"os"
     8  	"path/filepath"
     9  	"time"
    10  
    11  	"github.com/fatih/color"
    12  	"github.com/mattn/go-isatty"
    13  	"github.com/spf13/viper"
    14  	"github.com/turbot/steampipe/pkg/constants"
    15  	"github.com/turbot/steampipe/pkg/filepaths"
    16  )
    17  
    18  var logSink io.Writer
    19  
    20  const (
    21  	errorPrefix   = "[ Error   ]"
    22  	messagePrefix = "[ Message ]"
    23  	readyPrefix   = "[ Ready   ]"
    24  	waitPrefix    = "[ Wait    ]"
    25  )
    26  
    27  func initLogSink() {
    28  	if viper.GetBool(constants.ArgServiceMode) {
    29  		logName := fmt.Sprintf("dashboard-%s.log", time.Now().Format("2006-01-02"))
    30  		logPath := filepath.Join(filepaths.EnsureLogDir(), logName)
    31  		f, err := os.OpenFile(logPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
    32  		if err != nil {
    33  			fmt.Printf("failed to open dashboard manager log file: %s\n", err.Error())
    34  			os.Exit(3)
    35  		}
    36  		logSink = f
    37  	} else {
    38  		logSink = os.Stdout
    39  	}
    40  }
    41  
    42  func output(_ context.Context, prefix string, msg interface{}) {
    43  	if logSink == nil {
    44  		logSink = os.Stdout
    45  	}
    46  	fmt.Fprintf(logSink, "%s %v\n", prefix, msg)
    47  }
    48  
    49  func OutputMessage(ctx context.Context, msg string) {
    50  	output(ctx, applyColor(messagePrefix, color.HiGreenString), msg)
    51  }
    52  
    53  func OutputWarning(ctx context.Context, msg string) {
    54  	output(ctx, applyColor(messagePrefix, color.RedString), msg)
    55  }
    56  
    57  func OutputError(ctx context.Context, err error) {
    58  	output(ctx, applyColor(errorPrefix, color.RedString), err)
    59  }
    60  
    61  func outputReady(ctx context.Context, msg string) {
    62  	output(ctx, applyColor(readyPrefix, color.GreenString), msg)
    63  }
    64  
    65  func OutputWait(ctx context.Context, msg string) {
    66  	output(ctx, applyColor(waitPrefix, color.CyanString), msg)
    67  }
    68  
    69  func applyColor(str string, color func(format string, a ...interface{}) string) string {
    70  	if !isatty.IsTerminal(os.Stdout.Fd()) || viper.GetBool(constants.ArgServiceMode) {
    71  		return str
    72  	} else {
    73  		return color((str))
    74  	}
    75  }