fatih / color

Color package for Go (golang)
https://pkg.go.dev/github.com/fatih/color
MIT License
7.17k stars 610 forks source link

How to clear colored string? #150

Closed Charliego3 closed 2 years ago

Charliego3 commented 2 years ago

At the same time, output the log in the terminal and the file. I want the terminal to output colors, the file has no color characters. Register an interceptor in the log frame. How can I clear the colored string?

golog.Handle(func(log *golog.Log) (handled bool) {
   // clear the colored string
    return false
})
// no color in file
// colored on terminal
golog.Info(color.RedString("color message with log"))
fatih commented 2 years ago

You can create an individual color variable and do it on a per-color variable:

c := color.New(color.FgCyan)
c.Println("Prints cyan text")

c.DisableColor()
c.Println("This is printed without any color")

c.EnableColor()
c.Println("This prints again cyan...")

Or you can disable it globally with color.NoColor or clear it for existing colors via color.Unset(). It's in the readme.

Charliego3 commented 2 years ago

You can create an individual color variable and do it on a per-color variable:

c := color.New(color.FgCyan)
c.Println("Prints cyan text")

c.DisableColor()
c.Println("This is printed without any color")

c.EnableColor()
c.Println("This prints again cyan...")

Or you can disable it globally with color.NoColor or clear it for existing colors via color.Unset(). It's in the readme.

Sorry, maybe I made a mistake, color.NoColor or color.Unset() is global config. If it is set, all will not be displayed in color, which is not what I want. I meaning is color.RedString("color text") is converted to \x1b[31mcolor text \x1b[0m after, how to clear the color descriptor \x1b[\d+m in the string and replace it with regular? Can you provide an API to handle this. Thanks for your reply.

redText := color.RedString("color text")
fmt.Println(redText) // want to no color