1 // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
2 // Use of this source code is governed by a MIT style
3 // license that can be found in the LICENSE file.
14 "github.com/mattn/go-isatty"
18 green = string([]byte{27, 91, 57, 55, 59, 52, 50, 109})
19 white = string([]byte{27, 91, 57, 48, 59, 52, 55, 109})
20 yellow = string([]byte{27, 91, 57, 55, 59, 52, 51, 109})
21 red = string([]byte{27, 91, 57, 55, 59, 52, 49, 109})
22 blue = string([]byte{27, 91, 57, 55, 59, 52, 52, 109})
23 magenta = string([]byte{27, 91, 57, 55, 59, 52, 53, 109})
24 cyan = string([]byte{27, 91, 57, 55, 59, 52, 54, 109})
25 reset = string([]byte{27, 91, 48, 109})
29 // DisableConsoleColor disables color output in the console.
30 func DisableConsoleColor() {
34 // ErrorLogger returns a handlerfunc for any error type.
35 func ErrorLogger() HandlerFunc {
36 return ErrorLoggerT(ErrorTypeAny)
39 // ErrorLoggerT returns a handlerfunc for a given error type.
40 func ErrorLoggerT(typ ErrorType) HandlerFunc {
41 return func(c *Context) {
43 errors := c.Errors.ByType(typ)
50 // Logger instances a Logger middleware that will write the logs to gin.DefaultWriter.
51 // By default gin.DefaultWriter = os.Stdout.
52 func Logger() HandlerFunc {
53 return LoggerWithWriter(DefaultWriter)
56 // LoggerWithWriter instance a Logger middleware with the specified writter buffer.
57 // Example: os.Stdout, a file opened in write mode, a socket...
58 func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc {
61 if w, ok := out.(*os.File); !ok ||
62 (os.Getenv("TERM") == "dumb" || (!isatty.IsTerminal(w.Fd()) && !isatty.IsCygwinTerminal(w.Fd()))) ||
67 var skip map[string]struct{}
69 if length := len(notlogged); length > 0 {
70 skip = make(map[string]struct{}, length)
72 for _, path := range notlogged {
73 skip[path] = struct{}{}
77 return func(c *Context) {
80 path := c.Request.URL.Path
81 raw := c.Request.URL.RawQuery
86 // Log only when path is not being skipped
87 if _, ok := skip[path]; !ok {
90 latency := end.Sub(start)
92 clientIP := c.ClientIP()
93 method := c.Request.Method
94 statusCode := c.Writer.Status()
95 var statusColor, methodColor, resetColor string
97 statusColor = colorForStatus(statusCode)
98 methodColor = colorForMethod(method)
101 comment := c.Errors.ByType(ErrorTypePrivate).String()
104 path = path + "?" + raw
107 fmt.Fprintf(out, "[GIN] %v |%s %3d %s| %13v | %15s |%s %-7s %s %s\n%s",
108 end.Format("2006/01/02 - 15:04:05"),
109 statusColor, statusCode, resetColor,
112 methodColor, method, resetColor,
120 func colorForStatus(code int) string {
122 case code >= http.StatusOK && code < http.StatusMultipleChoices:
124 case code >= http.StatusMultipleChoices && code < http.StatusBadRequest:
126 case code >= http.StatusBadRequest && code < http.StatusInternalServerError:
133 func colorForMethod(method string) string {