github.com/artisanhe/tools@v1.0.1-0.20210607022958-19a8fef2eb04/gin_app/logger.go (about)

     1  package gin_app
     2  
     3  import (
     4  	"os"
     5  
     6  	"github.com/gin-gonic/gin"
     7  	"github.com/google/uuid"
     8  	"github.com/sirupsen/logrus"
     9  
    10  	"github.com/artisanhe/tools/courier/status_error"
    11  	"github.com/artisanhe/tools/duration"
    12  	"github.com/artisanhe/tools/log/context"
    13  	"github.com/artisanhe/tools/sign"
    14  )
    15  
    16  var (
    17  	REQUEST_ID_NAME = "x-request-id"
    18  	ProjectRef      = os.Getenv("PROJECT_REF")
    19  )
    20  
    21  func Logger() gin.HandlerFunc {
    22  	return func(c *gin.Context) {
    23  		if c.Request.URL.Path == "/healthz" {
    24  			return
    25  		}
    26  		d := duration.NewDuration()
    27  
    28  		reqID := c.Request.Header.Get(REQUEST_ID_NAME)
    29  
    30  		if reqID == "" {
    31  			reqID = uuid.New().String()
    32  		}
    33  
    34  		c.Set(REQUEST_ID_NAME, reqID)
    35  		c.Header("X-Reversion", ProjectRef)
    36  
    37  		context.SetLogID(reqID)
    38  		defer context.Close()
    39  
    40  		fields := logrus.Fields{
    41  			"tag":       "access",
    42  			//"log_id":     reqID,
    43  			"traceID":     reqID,
    44  			"request_id": reqID,
    45  			"remote_ip": c.ClientIP(),
    46  			"method":    c.Request.Method,
    47  			"pathname":  c.Request.URL.Path,
    48  		}
    49  		if accessKey := c.Request.Header.Get(sign.AccessKey); accessKey != "" {
    50  			fields["access_key"] = accessKey
    51  		}
    52  
    53  		c.Next()
    54  
    55  		fields["status"] = c.Writer.Status()
    56  		//fields["request_time"] = d.Get()
    57  		fields["cost"] = d.Get()
    58  
    59  		logger := logrus.WithFields(fields)
    60  
    61  		if len(c.Errors) > 0 {
    62  			for _, err := range c.Errors {
    63  				statusErr := status_error.FromError(err.Err)
    64  				if statusErr.Status() >= 500 {
    65  					logger.Errorf(statusErr.Error())
    66  				} else {
    67  					logger.Warnf(statusErr.Error())
    68  				}
    69  			}
    70  		} else {
    71  			logger.Info("")
    72  		}
    73  	}
    74  }