labstack / gommon

Common packages for Go
MIT License
540 stars 101 forks source link

Redirect stdout affects stderr #15

Closed suntong closed 6 years ago

suntong commented 6 years ago

Should redirecting stdout affect stderr?

Please take a look at this simple Color.go

The last two lines are from os.Stderr, and they will loose color when redirecting stdout:

image

Is it controlled by the OS or by the color package?

Thx!

suntong commented 6 years ago

Confirmed that is cause by color package.

 go run Color.go > /tmp/t
 cat /tmp/t
 echo abc def ghi | grep --color=always def | tee /tmp/t2
 cat /tmp/t2

Only the color package cause loosing the color. grep --color=always will keep it.

im-kulikov commented 6 years ago
// Example #1
    color.SetOutput(os.Stderr)
    color.Enable()
    color.Println(color.Black("black"),
        color.Red("red"),
        color.Green("green"),
        color.Yellow("yellow"),
        color.Blue("blue"),
        color.Magenta("magenta"),
        color.Cyan("cyan"),
        color.White("white"),
        color.Grey("grey"))

// Example #2
    color.Enable()
    fmt.Fprintln(os.Stderr, color.Black("black"),
        color.Red("red"),
        color.Green("green"),
        color.Yellow("yellow"),
        color.Blue("blue"),
        color.Magenta("magenta"),
        color.Cyan("cyan"),
        color.White("white"),
        color.Grey("grey"))

// Example #3
color.Enable()
fmt.Fprintf(os.Stderr, "%s %s %s\n",
        color.Red("red"), color.Yellow("yellow"), color.Green("green"))

Works fine

1 bash 2018-02-23 23-01-14
suntong commented 6 years ago

I.e., I don't think any one would do color.SetOutput(os.Stderr) in their normal program.

im-kulikov commented 6 years ago

@suntong see example 2 and 3

your problem solves by color.Enable()

type (
    Color struct {
        output   io.Writer
        disabled bool // always false by default
    }
)
suntong commented 6 years ago

Oh, got you. THX!

im-kulikov commented 6 years ago

@suntong no problem, you're welcome 😉