...

Source file src/github.com/gin-gonic/contrib/commonlog/commonlog.go

Documentation: github.com/gin-gonic/contrib/commonlog

     1  package commonlog
     2  
     3  import (
     4  	"bytes"
     5  	"io"
     6  	"strconv"
     7  	"sync"
     8  	"time"
     9  
    10  	"github.com/gin-gonic/gin"
    11  )
    12  
    13  // Instances a Logger middleware that will write the logs to gin.DefaultWriter
    14  // By default gin.DefaultWriter = os.Stdout
    15  func New() gin.HandlerFunc {
    16  	return NewWithWriter(gin.DefaultWriter)
    17  }
    18  
    19  // Instance a Logger middleware with the specified writer buffer.
    20  // Example: os.Stdout, a file opened in write mode, a socket...
    21  func NewWithWriter(out io.Writer) gin.HandlerFunc {
    22  	pool := &sync.Pool{
    23  		New: func() interface{} {
    24  			buf := new(bytes.Buffer)
    25  			return buf
    26  		},
    27  	}
    28  	return func(c *gin.Context) {
    29  		// Process request
    30  		c.Next()
    31  
    32  		//127.0.0.1 user-identifier frank [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326
    33  		w := pool.Get().(*bytes.Buffer)
    34  		w.Reset()
    35  		w.WriteString(c.ClientIP())
    36  		w.WriteString(" - - ")
    37  		w.WriteString(time.Now().Format("[02/Jan/2006:15:04:05 -0700] "))
    38  		w.WriteString("\"")
    39  		w.WriteString(c.Request.Method)
    40  		w.WriteString(" ")
    41  		w.WriteString(c.Request.URL.Path)
    42  		w.WriteString(" ")
    43  		w.WriteString(c.Request.Proto)
    44  		w.WriteString("\" ")
    45  		w.WriteString(strconv.Itoa(c.Writer.Status()))
    46  		w.WriteString(" ")
    47  		w.WriteString(strconv.Itoa(c.Writer.Size()))
    48  		w.WriteString("\n")
    49  
    50  		w.WriteTo(out)
    51  		pool.Put(w)
    52  	}
    53  }
    54  

View as plain text