fatih/color

set prefix

fprotimaru opened this issue · 2 comments

How can I set prefix time like log package?

vikpe commented

@fprotimaru I created a pretty printer with timestamp prefix [...msg].

Code

package term

import (
	"fmt"
	"time"

	"github.com/fatih/color"
)

const DELIMITER = "  "

var white = color.New(color.FgWhite).SprintFunc()

type PrettyPrinter struct {
	prefix string
}

func NewPrettyPrinter(prefix string, colorCode color.Attribute) PrettyPrinter {
	return PrettyPrinter{
		prefix: color.New(colorCode).Sprint(prefix),
	}
}

func (pp PrettyPrinter) Print(args ...any) {
	fmt.Print(timestamp(), DELIMITER, pp.prefix, DELIMITER)
	fmt.Println(args...)
}

func timestamp() string {
	currentTime := time.Now()
	format := "15:04:05"
	return white(currentTime.Format(format))
}

Usage

pp := term.NewPrettyPrinter("proxy", color.FgHiCyan)
pp.Print("hello", "world")
pp.Print(123)

Output

image

fatih commented

This question is not color related. Closing.