ToyBoomServer/common/logger.go
2024-09-02 18:07:30 +00:00

35 lines
742 B
Go

package common
import (
"context"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
func init() {
logrus.AddHook(&ObserveHook{})
}
func Logger(c context.Context) *logrus.Entry {
var uid, endpoint, header, method, traceid interface{}
if c != nil {
ginCtx, ok := c.(*gin.Context)
if ok {
uid = ginCtx.GetString(UserIDKey)
endpoint = ginCtx.Request.URL.Path
header = ginCtx.Request.Header
method = ginCtx.Request.Method
traceid = ginCtx.GetString(TraceIDKey)
}
}
logrus.SetFormatter(&logrus.JSONFormatter{})
return logrus.WithContext(c).
WithField(UserIDKey, uid).
WithField(EndpointKey, endpoint).
WithField(HeaderKey, header).
WithField(MethodKey, method).
WithField(TraceIDKey, traceid)
}