Skip to content
Myr

logger.go

This file

Path

logger.go

314 lines · 7.9 KiB · Go

Last changed by

chore(logger): allow skipping query string output (#4547)Jacob McSwainbefore adoptiondb30908

History of this file

Take it

1// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2// Use of this source code is governed by a MIT style3// license that can be found in the LICENSE file.45package gin67import (8	"fmt"9	"io"10	"net/http"11	"os"12	"time"1314	"github.com/mattn/go-isatty"15)1617type consoleColorModeValue int1819const (20	autoColor consoleColorModeValue = iota21	disableColor22	forceColor23)2425const (26	green   = "\033[97;42m"27	white   = "\033[90;47m"28	yellow  = "\033[90;43m"29	red     = "\033[97;41m"30	blue    = "\033[97;44m"31	magenta = "\033[97;45m"32	cyan    = "\033[97;46m"33	reset   = "\033[0m"34)3536var consoleColorMode = autoColor3738// LoggerConfig defines the config for Logger middleware.39type LoggerConfig struct {40	// Optional. Default value is gin.defaultLogFormatter41	Formatter LogFormatter4243	// Output is a writer where logs are written.44	// Optional. Default value is gin.DefaultWriter.45	Output io.Writer4647	// SkipPaths is a URL path array which logs are not written.48	// Optional.49	SkipPaths []string5051	// SkipQueryString indicates that query strings should not be written52	// for cases such as when API keys are passed via query strings.53	// Optional. Default value is false.54	SkipQueryString bool5556	// Skip is a Skipper that indicates which logs should not be written.57	// Optional.58	Skip Skipper59}6061// Skipper is a function to skip logs based on provided Context62type Skipper func(c *Context) bool6364// LogFormatter gives the signature of the formatter function passed to LoggerWithFormatter65type LogFormatter func(params LogFormatterParams) string6667// LogFormatterParams is the structure any formatter will be handed when time to log comes68type LogFormatterParams struct {69	Request *http.Request7071	// TimeStamp shows the time after the server returns a response.72	TimeStamp time.Time73	// StatusCode is HTTP response code.74	StatusCode int75	// Latency is how much time the server cost to process a certain request.76	Latency time.Duration77	// ClientIP equals Context's ClientIP method.78	ClientIP string79	// Method is the HTTP method given to the request.80	Method string81	// Path is a path the client requests.82	Path string83	// ErrorMessage is set if error has occurred in processing the request.84	ErrorMessage string85	// isTerm shows whether gin's output descriptor refers to a terminal.86	isTerm bool87	// BodySize is the size of the Response Body88	BodySize int89	// Keys are the keys set on the request's context.90	Keys map[any]any91}9293// StatusCodeColor is the ANSI color for appropriately logging http status code to a terminal.94func (p *LogFormatterParams) StatusCodeColor() string {95	code := p.StatusCode9697	switch {98	case code >= http.StatusContinue && code < http.StatusOK:99		return white100	case code >= http.StatusOK && code < http.StatusMultipleChoices:101		return green102	case code >= http.StatusMultipleChoices && code < http.StatusBadRequest:103		return white104	case code >= http.StatusBadRequest && code < http.StatusInternalServerError:105		return yellow106	default:107		return red108	}109}110111// LatencyColor is the ANSI color for latency112func (p *LogFormatterParams) LatencyColor() string {113	latency := p.Latency114	switch {115	case latency < time.Millisecond*100:116		return white117	case latency < time.Millisecond*200:118		return green119	case latency < time.Millisecond*300:120		return cyan121	case latency < time.Millisecond*500:122		return blue123	case latency < time.Second:124		return yellow125	case latency < time.Second*2:126		return magenta127	default:128		return red129	}130}131132// MethodColor is the ANSI color for appropriately logging http method to a terminal.133func (p *LogFormatterParams) MethodColor() string {134	method := p.Method135136	switch method {137	case http.MethodGet:138		return blue139	case http.MethodPost:140		return cyan141	case http.MethodPut:142		return yellow143	case http.MethodDelete:144		return red145	case http.MethodPatch:146		return green147	case http.MethodHead:148		return magenta149	case http.MethodOptions:150		return white151	default:152		return reset153	}154}155156// ResetColor resets all escape attributes.157func (p *LogFormatterParams) ResetColor() string {158	return reset159}160161// IsOutputColor indicates whether can colors be outputted to the log.162func (p *LogFormatterParams) IsOutputColor() bool {163	return consoleColorMode == forceColor || (consoleColorMode == autoColor && p.isTerm)164}165166// defaultLogFormatter is the default log format function Logger middleware uses.167var defaultLogFormatter = func(param LogFormatterParams) string {168	var statusColor, methodColor, resetColor, latencyColor string169	if param.IsOutputColor() {170		statusColor = param.StatusCodeColor()171		methodColor = param.MethodColor()172		resetColor = param.ResetColor()173		latencyColor = param.LatencyColor()174	}175176	switch {177	case param.Latency > time.Minute:178		param.Latency = param.Latency.Truncate(time.Second * 10)179	case param.Latency > time.Second:180		param.Latency = param.Latency.Truncate(time.Millisecond * 10)181	case param.Latency > time.Millisecond:182		param.Latency = param.Latency.Truncate(time.Microsecond * 10)183	}184185	return fmt.Sprintf("[GIN] %v |%s %3d %s|%s %8v %s| %15s |%s %-7s %s %#v\n%s",186		param.TimeStamp.Format("2006/01/02 - 15:04:05"),187		statusColor, param.StatusCode, resetColor,188		latencyColor, param.Latency, resetColor,189		param.ClientIP,190		methodColor, param.Method, resetColor,191		param.Path,192		param.ErrorMessage,193	)194}195196// DisableConsoleColor disables color output in the console.197func DisableConsoleColor() {198	consoleColorMode = disableColor199}200201// ForceConsoleColor force color output in the console.202func ForceConsoleColor() {203	consoleColorMode = forceColor204}205206// ErrorLogger returns a HandlerFunc for any error type.207func ErrorLogger() HandlerFunc {208	return ErrorLoggerT(ErrorTypeAny)209}210211// ErrorLoggerT returns a HandlerFunc for a given error type.212func ErrorLoggerT(typ ErrorType) HandlerFunc {213	return func(c *Context) {214		c.Next()215		errors := c.Errors.ByType(typ)216		if len(errors) > 0 {217			c.JSON(-1, errors)218		}219	}220}221222// Logger instances a Logger middleware that will write the logs to gin.DefaultWriter.223// By default, gin.DefaultWriter = os.Stdout.224func Logger() HandlerFunc {225	return LoggerWithConfig(LoggerConfig{})226}227228// LoggerWithFormatter instance a Logger middleware with the specified log format function.229func LoggerWithFormatter(f LogFormatter) HandlerFunc {230	return LoggerWithConfig(LoggerConfig{231		Formatter: f,232	})233}234235// LoggerWithWriter instance a Logger middleware with the specified writer buffer.236// Example: os.Stdout, a file opened in write mode, a socket...237func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc {238	return LoggerWithConfig(LoggerConfig{239		Output:    out,240		SkipPaths: notlogged,241	})242}243244// LoggerWithConfig instance a Logger middleware with config.245func LoggerWithConfig(conf LoggerConfig) HandlerFunc {246	formatter := conf.Formatter247	if formatter == nil {248		formatter = defaultLogFormatter249	}250251	out := conf.Output252	if out == nil {253		out = DefaultWriter254	}255256	notlogged := conf.SkipPaths257258	isTerm := true259260	if w, ok := out.(*os.File); !ok || os.Getenv("TERM") == "dumb" ||261		(!isatty.IsTerminal(w.Fd()) && !isatty.IsCygwinTerminal(w.Fd())) {262		isTerm = false263	}264265	var skip map[string]struct{}266267	if length := len(notlogged); length > 0 {268		skip = make(map[string]struct{}, length)269270		for _, path := range notlogged {271			skip[path] = struct{}{}272		}273	}274275	return func(c *Context) {276		// Start timer277		start := time.Now()278		path := c.Request.URL.Path279		raw := c.Request.URL.RawQuery280281		// Process request282		c.Next()283284		// Log only when it is not being skipped285		if _, ok := skip[path]; ok || (conf.Skip != nil && conf.Skip(c)) {286			return287		}288289		param := LogFormatterParams{290			Request: c.Request,291			isTerm:  isTerm,292			Keys:    c.Keys,293		}294295		// Stop timer296		param.TimeStamp = time.Now()297		param.Latency = param.TimeStamp.Sub(start)298299		param.ClientIP = c.ClientIP()300		param.Method = c.Request.Method301		param.StatusCode = c.Writer.Status()302		param.ErrorMessage = c.Errors.ByType(ErrorTypePrivate).String()303304		param.BodySize = c.Writer.Size()305306		if raw != "" && !conf.SkipQueryString {307			path = path + "?" + raw308		}309310		param.Path = path311312		fmt.Fprint(out, formatter(param))313	}314}