gin_logger

package
v0.0.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 17, 2025 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var GinZapHandler gin.HandlerFunc = func(c *gin.Context) {
	start := time.Now()

	path := c.Request.URL.Path
	query := c.Request.URL.RawQuery
	c.Next()
	track := true

	if track {
		end := time.Now()
		latency := end.Sub(start)

		fields := []any{
			"status", c.Writer.Status(),
			"method", c.Request.Method,
			"path", path,
			"query", query,
			"ip", c.ClientIP(),
			"ua", c.Request.UserAgent(),
			"latency", latency,
		}
		ctx := getCtxFromGinContext(c)

		if len(c.Errors) > 0 {

			errorMsg := ""
			for i, e := range c.Errors.Errors() {
				errorMsg += fmt.Sprintf("[%d]: %s\n", i, e)
			}
			loggers.CLogw(ctx, zap.ErrorLevel, 2, errorMsg, fields...)
		} else {
			msg := fmt.Sprintf("%s %s", c.Request.Method, c.Request.URL.Path)
			loggers.CLogw(ctx, zap.InfoLevel, 2, msg, fields...)
		}
	}
}
View Source
var GinZapRecoveryHandler gin.HandlerFunc = func(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			// Check for a broken connection, as it is not really a
			// condition that warrants a panic stack trace.
			var brokenPipe bool
			if ne, ok := err.(*net.OpError); ok {
				if se, ok := ne.Err.(*os.SyscallError); ok {
					if strings.Contains(strings.ToLower(se.Error()), "broken pipe") ||
						strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
						brokenPipe = true
					}
				}
			}

			httpRequest, _ := httputil.DumpRequest(c.Request, false)
			ctx := getCtxFromGinContext(c)

			if brokenPipe {
				loggers.CLogw(
					ctx, zap.ErrorLevel,
					2,
					fmt.Sprintf("broken pipe request: %s err: %s", string(httpRequest), err),
				)

				c.Error(err.(error))
				c.Abort()
				return
			}

			loggers.CLogw(
				ctx, zap.ErrorLevel,
				2,
				fmt.Sprintf("[Recovery from panic] request: %s err: %s", string(httpRequest), err),
			)

			c.AbortWithStatus(http.StatusInternalServerError)
		}
	}()
	c.Next()
}

Functions

func GetGinTraceCtx

func GetGinTraceCtx(ctx context.Context, c *gin.Context) context.Context

func SetupGinEngineZapLogger

func SetupGinEngineZapLogger(r *gin.Engine, zapLogger *zap.Logger)

SetupGinEngineZapLogger sets up the gin engine log with zap logger.

func SetupGinZapLogger

func SetupGinZapLogger(zapLogger *zap.Logger)

SetupGinZapLogger sets up the gin debug log with zap logger.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL