123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- package hieda_ginutil
- import (
- "fmt"
- "git.swzry.com/zry/GoHiedaLogger/hiedalog"
- "github.com/gin-gonic/gin"
- "strconv"
- "time"
- )
- type GinLoggerConfig struct {
- Logger *hiedalog.HiedaLogger
- ModuleName string
- LevelMapFunc func(int) string
- }
- func GinLoggerWithStringLogger(config GinLoggerConfig) gin.HandlerFunc {
- return func(c *gin.Context) {
- start := time.Now()
- path := c.Request.URL.Path
- raw := c.Request.URL.RawQuery
- c.Next()
- end := time.Now()
- latency := end.Sub(start)
- clientIP := c.ClientIP()
- method := c.Request.Method
- statusCode := c.Writer.Status()
- lvs := config.LevelMapFunc(statusCode)
- // comment := c.Errors.ByType(gin.ErrorTypePrivate).String()
- if raw != "" {
- path = path + "?" + raw
- }
- sv := fmt.Sprintf("%v | %3d | %13v | %15s | %-7s %s",
- end.Format("2006/01/02 - 15:04:05"),
- statusCode,
- latency,
- clientIP,
- method,
- path,
- )
- config.Logger.LogString(config.ModuleName, lvs, sv)
- }
- }
- func GinLoggerWithComplexLogger(config GinLoggerConfig) gin.HandlerFunc {
- return func(c *gin.Context) {
- start := time.Now()
- path := c.Request.URL.Path
- raw := c.Request.URL.RawQuery
- c.Next()
- end := time.Now()
- latency := end.Sub(start)
- clientIP := c.ClientIP()
- method := c.Request.Method
- statusCode := c.Writer.Status()
- lvs := config.LevelMapFunc(statusCode)
- comment := c.Errors.ByType(gin.ErrorTypePrivate).String()
- if raw != "" {
- path = path + "?" + raw
- }
- mv := map[string]string{
- "time": end.Format("2006/01/02 - 15:04:05"),
- "status": strconv.Itoa(statusCode),
- "latency": fmt.Sprintf("%13v", latency),
- "clientIP": clientIP,
- "method": method,
- "path": path,
- "comment": comment,
- }
- config.Logger.LogComplex(config.ModuleName, lvs, mv)
- }
- }
- func GetSimpleLevelMapFunc(Http1xx, Http2xx, Http3xx, Http4xx, Http5xx, Default string) func(int) string {
- return func(code int) string {
- switch {
- case code >= 100 && code < 200:
- return Http1xx
- case code >= 200 && code < 300:
- return Http2xx
- case code >= 300 && code < 400:
- return Http3xx
- case code >= 400 && code < 500:
- return Http4xx
- case code >= 500 && code < 600:
- return Http5xx
- default:
- return Default
- }
- }
- }
- func GetDefaultLevelMapFunc() func(int) string {
- return GetSimpleLevelMapFunc(hiedalog.DLN_INFO, hiedalog.DLN_INFO, hiedalog.DLN_INFO, hiedalog.DLN_WARN, hiedalog.DLN_ERROR, hiedalog.DLN_ERROR)
- }
|