From 411f65257a94712ed620c0e0b1666806a5a95cce Mon Sep 17 00:00:00 2001 From: Pieter Claerhout Date: Thu, 12 Dec 2019 15:45:54 +0100 Subject: [PATCH] Fixed the color output on Windows Colored output seems to be broken on Windows Command Prompt https://github.com/pieterclaerhout/go-log/issues/8 --- cmd/go-log/main.go | 1 + go.mod | 2 +- logger.go | 5 ++--- logger_internal.go | 18 +++++++++--------- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/cmd/go-log/main.go b/cmd/go-log/main.go index e4ab2f2..ae64268 100644 --- a/cmd/go-log/main.go +++ b/cmd/go-log/main.go @@ -5,6 +5,7 @@ import ( ) func main() { + log.DebugMode = true log.DebugSQLMode = true log.PrintTimestamp = true diff --git a/go.mod b/go.mod index 500ae84..b2b93e1 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,7 @@ go 1.13 require ( github.com/fatih/color v1.7.0 github.com/go-errors/errors v1.0.1 - github.com/mattn/go-colorable v0.1.4 // indirect + github.com/mattn/go-colorable v0.1.4 github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b github.com/pieterclaerhout/go-formatter v1.0.2 github.com/pkg/errors v0.8.1 diff --git a/logger.go b/logger.go index 3b4d42d..a4adbce 100644 --- a/logger.go +++ b/logger.go @@ -2,7 +2,6 @@ package log import ( "fmt" - "io" "os" "strings" "time" @@ -32,10 +31,10 @@ var DebugSQLMode = false var TimeZone *time.Location // Stdout is the writer to where the stdout messages should be written (defaults to os.Stdout) -var Stdout io.Writer = os.Stdout +var Stdout *os.File = os.Stdout // Stderr is the writer to where the stderr messages should be written (defaults to os.Stderr) -var Stderr io.Writer = os.Stderr +var Stderr *os.File = os.Stderr // DefaultTimeFormat is the default format to use for the timestamps var DefaultTimeFormat = "2006-01-02 15:04:05.000" diff --git a/logger_internal.go b/logger_internal.go index 6116dde..8ec07dd 100644 --- a/logger_internal.go +++ b/logger_internal.go @@ -8,6 +8,7 @@ import ( "time" "github.com/fatih/color" + "github.com/mattn/go-colorable" ) var logMutex = &sync.Mutex{} @@ -48,8 +49,6 @@ func formatSeparator(message string, separator string, length int) string { func printMessage(level string, message string) { - logMutex.Lock() - level = strings.ToUpper(level) if PrintTimestamp { @@ -60,20 +59,21 @@ func printMessage(level string, message string) { formattedTime := tstamp.Format(TimeFormat) message = formattedTime + " | " + level + " | " + message } - if PrintColors { - if color, ok := colors[level]; ok { - message = color.Sprint(message) - } - } w := Stdout if level == "ERROR" || level == "FATAL" { w = Stderr } - w.Write([]byte(message + "\n")) + if PrintColors { + cw := colorable.NewColorable(w) + if c, ok := colors[level]; ok { + c.Fprintln(cw, message) + return + } + } - logMutex.Unlock() + w.Write([]byte(message + "\n")) }