From 70ada0c7b6a05d50e8508428d49a1274046d57a8 Mon Sep 17 00:00:00 2001 From: David Irvine Date: Thu, 17 Nov 2016 16:31:00 -0500 Subject: [PATCH] Logger: skip ANSI color commands if output is not a tty --- logger.go | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/logger.go b/logger.go index d56bc62..b4743a7 100644 --- a/logger.go +++ b/logger.go @@ -7,7 +7,10 @@ package gin import ( "fmt" "io" + "os" "time" + + "golang.org/x/crypto/ssh/terminal" ) var ( @@ -44,6 +47,11 @@ func Logger() HandlerFunc { // LoggerWithWriter instance a Logger middleware with the specified writter buffer. // Example: os.Stdout, a file opened in write mode, a socket... func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc { + isTerm := true + if outFile, ok := out.(*os.File); ok { + isTerm = terminal.IsTerminal(int(outFile.Fd())) + } + var skip map[string]struct{} if length := len(notlogged); length > 0 { @@ -71,8 +79,11 @@ func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc { clientIP := c.ClientIP() method := c.Request.Method statusCode := c.Writer.Status() - statusColor := colorForStatus(statusCode) - methodColor := colorForMethod(method) + var statusColor, methodColor string + if isTerm { + statusColor = colorForStatus(statusCode) + methodColor = colorForMethod(method) + } comment := c.Errors.ByType(ErrorTypePrivate).String() fmt.Fprintf(out, "[GIN] %v |%s %3d %s| %13v | %s |%s %s %-7s %s\n%s",