zapx

package module
v0.1.10 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2024 License: MIT Imports: 25 Imported by: 4

README

Zapx GoDoc

Zapx provides a zap logger with Stackdriver format output. It aims to integreate with GRPC and Opensensus. It also comes with extra features. Such as:

  • Slack Notification
  • Custom Error endocer
  • Extract tracing & GRPC information from context
  • Stackdriver Label
  • Extract Request ID from context metadata

Usage

go get -u github.com/lixin9311/zapx
package main

import (
 "errors"
 "time"

 "github.com/lixin9311/zapx"
 "go.uber.org/zap"
 "go.uber.org/zap/zapcore"
)

type customError struct {
 err error
}

// MarshalLogObject implements zap.ObjectMarshaler
func (e *customError) MarshalLogObject(enc zapcore.ObjectEncoder) error {
 if e == nil {
  enc.AddString("error", "nil")
  return nil
 }
 enc.AddString("error", e.err.Error())
 enc.AddString("message", "custom message")
 return nil
}

func main() {
 logger := zapx.Zap(zapcore.DebugLevel,
  zapx.WithProjectID("example-project"),
  zapx.WithService("example-service"),
  zapx.WithSlackURL("https://slack-webhook"),
  zapx.WithVersion("v0.0.1"),
  zapx.WithErrorParser(func(e error) (zapcore.ObjectMarshaler, bool) {
   return &customError{e}, true
  }),
 )

 zap.ReplaceGlobals(logger)
 zap.L().Debug("hello world", zap.Error(errors.New("example error")),
  zapx.Label("foo-label", "foo"), zapx.Label("bar-label", "bar"),
  zapx.Request(zapx.HTTPRequestEntry{
   RequestMethod: "GET",
   RequestURL:    "http://example.com",
   Status:        200,
   RequestSize:   1024,
   UserAgent:     "curl",
   RemoteIP:      "8.8.8.8",
   Referer:       "http://example.com",
   Latency:       time.Second,
  }),
 )
}

See https://pkg.go.dev/github.com/lixin9311/zapx to view the documentation.

Contributing

  • I would like to keep this library as small as possible.
  • Please don't send a PR without opening an issue and discussing it first.
  • If proposed change is not a common use case, I will probably not accept it.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	RequestIDMetadataKey = "x-request-id"
)
View Source
var StackdriverEncoderConfig = zapcore.EncoderConfig{
	MessageKey:    "message",
	LevelKey:      "severity",
	TimeKey:       "eventTime",
	NameKey:       "logger",
	CallerKey:     "caller",
	StacktraceKey: "stacktrace",
	LineEnding:    zapcore.DefaultLineEnding,
	EncodeLevel: func(lv zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
		var s string
		switch lv {
		case zapcore.DebugLevel:
			s = "DEBUG"
		case zapcore.InfoLevel:
			s = "INFO"
		case zapcore.WarnLevel:
			s = "WARNING"
		case zapcore.ErrorLevel:
			s = "ERROR"
		case zapcore.DPanicLevel:
			s = "CRITICAL"
		case zapcore.PanicLevel:
			s = "ALERT"
		case zapcore.FatalLevel:
			s = "EMERGENCY"
		}

		enc.AppendString(s)
	},
	EncodeTime:     zapcore.ISO8601TimeEncoder,
	EncodeDuration: zapcore.SecondsDurationEncoder,
	EncodeCaller:   zapcore.ShortCallerEncoder,
}

StackdriverEncoderConfig is a encoder config for stackdriver.

Functions

func Context

func Context(ctx context.Context) zapcore.Field

Context constructs a field that carries trace span & grpc method if possible.

func Label

func Label(key, val string) zapcore.Field

func Metadata

func Metadata(ctx context.Context) zapcore.Field

Metadata constructs a field that carries metadata from context.

func Proto added in v0.1.2

func Proto(key string, val proto.Message) zapcore.Field

func Request

func Request(req HTTPRequestEntry) zapcore.Field

func Slack added in v0.1.1

func Slack(url ...string) zapcore.Field

func Visitor added in v0.1.10

func Visitor(logger *zap.Logger) func(f *flag.Flag)

Visitor will dump all the flags to Info level logger. It will automatically redact sensitive fields, name of which contains `key, secret, password, dsn` keywords

func VisitorP added in v0.1.10

func VisitorP(logger *zap.Logger) func(f *pflag.Flag)

VisitorP will dump all the flags to Info level logger. It will automatically redact sensitive fields, name of which contains `key, secret, password, dsn` keywords

func Zap

func Zap(level zapcore.Level, opts ...Option) *zap.Logger

Zap returns a zap logger configured to output logs to stdout and stderr.

Types

type HTTPRequestEntry

type HTTPRequestEntry struct {
	Request       *http.Request
	RequestMethod string
	RequestURL    string
	RequestSize   int64
	Status        int
	ResponseSize  int64
	UserAgent     string
	RemoteIP      string
	Referer       string
	Latency       time.Duration
}

HTTPRequestEntry is information about the HTTP request associated with this log entry. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#HttpRequest

func (HTTPRequestEntry) MarshalLogObject

func (t HTTPRequestEntry) MarshalLogObject(e zapcore.ObjectEncoder) error

MarshalLogObject is ObjectMarshaler implementation.

type Option

type Option func(*option)

func WithErrorParser

func WithErrorParser(parser func(error) (zapcore.ObjectMarshaler, bool)) Option

func WithProjectID

func WithProjectID(id string) Option

func WithService

func WithService(name string) Option

func WithSlackURL

func WithSlackURL(url string) Option

WithSlackURL sets the slack hook url

func WithVersion

func WithVersion(ver string) Option

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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