...

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

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

     1  // Package ginrus provides log handling using logrus package.
     2  //
     3  // Based on github.com/stephenmuss/ginerus but adds more options.
     4  package ginrus
     5  
     6  import (
     7  	"time"
     8  
     9  	"github.com/gin-gonic/gin"
    10  	"github.com/sirupsen/logrus"
    11  )
    12  
    13  type loggerEntryWithFields interface {
    14  	WithFields(fields logrus.Fields) *logrus.Entry
    15  }
    16  
    17  // Ginrus returns a gin.HandlerFunc (middleware) that logs requests using logrus.
    18  //
    19  // Requests with errors are logged using logrus.Error().
    20  // Requests without errors are logged using logrus.Info().
    21  //
    22  // It receives:
    23  //   1. A time package format string (e.g. time.RFC3339).
    24  //   2. A boolean stating whether to use UTC time zone or local.
    25  func Ginrus(logger loggerEntryWithFields, timeFormat string, utc bool) gin.HandlerFunc {
    26  	return func(c *gin.Context) {
    27  		start := time.Now()
    28  		// some evil middlewares modify this values
    29  		path := c.Request.URL.Path
    30  		c.Next()
    31  
    32  		end := time.Now()
    33  		latency := end.Sub(start)
    34  		if utc {
    35  			end = end.UTC()
    36  		}
    37  
    38  		entry := logger.WithFields(logrus.Fields{
    39  			"status":     c.Writer.Status(),
    40  			"method":     c.Request.Method,
    41  			"path":       path,
    42  			"ip":         c.ClientIP(),
    43  			"latency":    latency,
    44  			"user-agent": c.Request.UserAgent(),
    45  			"time":       end.Format(timeFormat),
    46  		})
    47  
    48  		if len(c.Errors) > 0 {
    49  			// Append error field if this is an erroneous request.
    50  			entry.Error(c.Errors.String())
    51  		} else {
    52  			entry.Info()
    53  		}
    54  	}
    55  }
    56  

View as plain text