mirror of
				https://github.com/gin-gonic/gin.git
				synced 2025-11-04 09:12:12 +08:00 
			
		
		
		
	Adds source IP in built-in logger
This commit is contained in:
		
							parent
							
								
									f8d85c1b4d
								
							
						
					
					
						commit
						c1775e85cc
					
				
							
								
								
									
										22
									
								
								logger.go
									
									
									
									
									
								
							
							
						
						
									
										22
									
								
								logger.go
									
									
									
									
									
								
							@ -1,7 +1,6 @@
 | 
			
		||||
package gin
 | 
			
		||||
 | 
			
		||||
import (
 | 
			
		||||
	"fmt"
 | 
			
		||||
	"log"
 | 
			
		||||
	"os"
 | 
			
		||||
	"time"
 | 
			
		||||
@ -27,7 +26,9 @@ var (
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
func Logger() HandlerFunc {
 | 
			
		||||
	logger := log.New(os.Stdout, "", 0)
 | 
			
		||||
	stdlogger := log.New(os.Stdout, "", 0)
 | 
			
		||||
	//errlogger := log.New(os.Stderr, "", 0)
 | 
			
		||||
 | 
			
		||||
	return func(c *Context) {
 | 
			
		||||
		// Start timer
 | 
			
		||||
		start := time.Now()
 | 
			
		||||
@ -35,6 +36,18 @@ func Logger() HandlerFunc {
 | 
			
		||||
		// Process request
 | 
			
		||||
		c.Next()
 | 
			
		||||
 | 
			
		||||
		// save the IP of the requester
 | 
			
		||||
		requester := c.Req.Header.Get("X-Real-IP")
 | 
			
		||||
		// if the requester-header is empty, check the forwarded-header
 | 
			
		||||
		if requester == "" {
 | 
			
		||||
			requester = c.Req.Header.Get("X-Forwarded-For")
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		// if the requester is still empty, use the hard-coded address from the socket
 | 
			
		||||
		if requester == "" {
 | 
			
		||||
			requester = c.Req.RemoteAddr
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		var color string
 | 
			
		||||
		code := c.Writer.Status()
 | 
			
		||||
		switch {
 | 
			
		||||
@ -48,17 +61,18 @@ func Logger() HandlerFunc {
 | 
			
		||||
			color = red
 | 
			
		||||
		}
 | 
			
		||||
		latency := time.Since(start)
 | 
			
		||||
		logger.Printf("[GIN] %v |%s %3d %s| %12v | %3.1f%% | %3s | %s\n",
 | 
			
		||||
		stdlogger.Printf("[GIN] %v |%s %3d %s| %12v | %3.1f%% | %s %4s %s\n",
 | 
			
		||||
			time.Now().Format("2006/01/02 - 15:04:05"),
 | 
			
		||||
			color, c.Writer.Status(), reset,
 | 
			
		||||
			latency,
 | 
			
		||||
			c.Engine.CacheStress()*100,
 | 
			
		||||
			requester,
 | 
			
		||||
			c.Req.Method, c.Req.URL.Path,
 | 
			
		||||
		)
 | 
			
		||||
 | 
			
		||||
		// Calculate resolution time
 | 
			
		||||
		if len(c.Errors) > 0 {
 | 
			
		||||
			fmt.Println(c.Errors.String())
 | 
			
		||||
			stdlogger.Println(c.Errors.String())
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user