iriszap

package module
v0.0.0-...-a252b7a Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2024 License: MIT Imports: 9 Imported by: 0

README

zap

Alternative logging through zap after the #2125 feature request. A clone of https://github.com/gin-contrib/zap.

Usage

Start using it

Download and install it:

go get github.com/iris-contrib/middleware/zap@master

Import it in your code:

import "github.com/iris-contrib/middleware/zap"

Example

See the example.

package main

import (
	"fmt"
	"time"

	iriszap "github.com/iris-contrib/middleware/zap"
	"github.com/kataras/iris/v12"
	"go.uber.org/zap"
)

func main() {
	app := iris.New()

	logger, _ := zap.NewProduction()

	// Add a iriszap middleware, which:
	//   - Logs all requests, like a combined access and error log.
	//   - Logs to stdout.
	//   - RFC3339 with UTC time format.
	app.Use(iriszap.New(logger, time.RFC3339, true))

	// Logs all panic to error log
	//   - stack means whether output the stack info.
	app.Use(iriszap.RecoveryWithZap(logger, true))

	// Example ping request.
	app.Get("/ping", func(ctx iris.Context) {
		ctx.Text("pong " + fmt.Sprint(time.Now().Unix()))
	})

	// Example when panic happen.
	app.Get("/panic", func(ctx iris.Context) {
		panic("An unexpected error happen!")
	})

	// Listen and Server in 0.0.0.0:8080
	app.Listen(":8080")
}

Skip logging

When you want to skip logging for specific path, please use NewWithConfig


app.Use(NewWithConfig(utcLogger, &Config{
  TimeFormat: time.RFC3339,
  UTC: true,
  SkipPaths: []string{"/no_log"},
}))

Custom Zap fields

Example for custom log request body, response request ID or log Open Telemetry TraceID.

func main() {
	app := iris.New()

	logger, _ := zap.NewProduction()

	app.Use(iriszap.NewWithConfig(logger, &iriszap.Config{
		UTC:        true,
		TimeFormat: time.RFC3339,
		Context: iriszap.Fn(func(ctx iris.Context) []zapcore.Field {
			req := ctx.Request()

			fields := []zapcore.Field{}
			// log request ID
			if requestID := ctx.ResponseWriter().Header().Get("X-Request-Id"); requestID != "" {
				fields = append(fields, zap.String("request_id", requestID))
			}

			// log trace and span ID
			if trace.SpanFromContext(req.Context()).SpanContext().IsValid() {
				fields = append(fields, zap.String("trace_id", trace.SpanFromContext(req.Context()).SpanContext().TraceID().String()))
				fields = append(fields, zap.String("span_id", trace.SpanFromContext(req.Context()).SpanContext().SpanID().String()))
			}

			// log request body
			var body []byte
			var buf bytes.Buffer
			tee := io.TeeReader(req.Body, &buf)
			body, _ = io.ReadAll(tee)
			req.Body = io.NopCloser(&buf)
			fields = append(fields, zap.String("body", string(body)))

			return fields
		}),
	}))

	// Example ping request.
	app.Get("/ping", func(ctx iris.Context) {
		ctx.Header("X-Request-Id", "1234-5678-9012")
		ctx.Text("pong " + fmt.Sprint(time.Now().Unix()))
	})

	app.Post("/ping", func(ctx iris.Context) {
		ctx.Header("X-Request-Id", "9012-5678-1234")
		ctx.Text("pong " + fmt.Sprint(time.Now().Unix()))
	})

	// Listen and Server in 0.0.0.0:8080
	app.Listen(":8080")
}

Documentation

Overview

Package iriszap provides log handling using zap package.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CustomRecoveryWithZap

func CustomRecoveryWithZap(logger *zap.Logger, stack bool, recovery func(iris.Context, interface{})) iris.Handler

CustomRecoveryWithZap returns an iris.Handler (middleware) with a custom recovery handler that recovers from any panics and logs requests using uber-go/zap. All errors are logged using zap.Error(). stack means whether output the stack info. The stack info is easy to find where the error occurs but the stack info is too large.

func New

func New(logger *zap.Logger, timeFormat string, utc bool) iris.Handler

New returns an iris.Handler (middleware) that logs requests using uber-go/zap.

Requests with errors are logged using zap.Error(). Requests without errors are logged using zap.Info().

It receives:

  1. A time package format string (e.g. time.RFC3339).
  2. A boolean stating whether to use UTC time zone or local.

func NewWithConfig

func NewWithConfig(logger *zap.Logger, conf *Config) iris.Handler

NewWithConfig returns an iris.Handler using configs.

func RecoveryWithZap

func RecoveryWithZap(logger *zap.Logger, stack bool) iris.Handler

RecoveryWithZap returns an iris.Handler (middleware) that recovers from any panics and logs requests using uber-go/zap. All errors are logged using zap.Error(). stack means whether output the stack info. The stack info is easy to find where the error occurs but the stack info is too large.

Types

type Config

type Config struct {
	TimeFormat string
	UTC        bool
	SkipPaths  []string
	Context    Fn
}

Config is config setting for iriszap.

type Fn

type Fn func(ctx iris.Context) []zapcore.Field

Directories

Path Synopsis
_examples

Jump to

Keyboard shortcuts

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