Merge pull request #744 from aviddiviner/logger-fix

Logger: skip ANSI color commands if output is not a tty
This commit is contained in:
Bo-Yi Wu 2016-12-01 06:20:24 +08:00 committed by GitHub
commit c3bfd69303
1 changed files with 13 additions and 2 deletions

View File

@ -7,7 +7,10 @@ package gin
import ( import (
"fmt" "fmt"
"io" "io"
"os"
"time" "time"
"golang.org/x/crypto/ssh/terminal"
) )
var ( var (
@ -44,6 +47,11 @@ func Logger() HandlerFunc {
// LoggerWithWriter instance a Logger middleware with the specified writter buffer. // LoggerWithWriter instance a Logger middleware with the specified writter buffer.
// Example: os.Stdout, a file opened in write mode, a socket... // Example: os.Stdout, a file opened in write mode, a socket...
func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc { 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{} var skip map[string]struct{}
if length := len(notlogged); length > 0 { if length := len(notlogged); length > 0 {
@ -71,8 +79,11 @@ func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc {
clientIP := c.ClientIP() clientIP := c.ClientIP()
method := c.Request.Method method := c.Request.Method
statusCode := c.Writer.Status() statusCode := c.Writer.Status()
statusColor := colorForStatus(statusCode) var statusColor, methodColor string
methodColor := colorForMethod(method) if isTerm {
statusColor = colorForStatus(statusCode)
methodColor = colorForMethod(method)
}
comment := c.Errors.ByType(ErrorTypePrivate).String() comment := c.Errors.ByType(ErrorTypePrivate).String()
fmt.Fprintf(out, "[GIN] %v |%s %3d %s| %13v | %s |%s %s %-7s %s\n%s", fmt.Fprintf(out, "[GIN] %v |%s %3d %s| %13v | %s |%s %s %-7s %s\n%s",