ctxzap

package module
v0.0.0-...-11ddc06 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2023 License: MIT Imports: 2 Imported by: 0

README

ctxzap

Bind zap to context, built-in support for grpc.

Install

go get github.com/acrazing/ctxzap

Quick start

package main

import (
    "context"
    "github.com/acrazing/ctxzap"
    "github.com/acrazing/ctxzap/grpc_zap"
    "go.uber.org/zap"
    "google.golang.org/grpc"
)

func main() {
	// get your logger
    logger := zap.NewExample()

	// inject interceptors
    _ = grpc.NewServer(
        grpc.ChainUnaryInterceptor(
            grpc_zap.UnaryServerInterceptor(logger, grpc_zap.WithAccessLog(true, true)),
        ),
        grpc.ChainStreamInterceptor(
            grpc_zap.StreamServerInterceptor(logger, grpc_zap.WithEventLog(true, true)),
        ),
    )

	// print log
    // In any context based method called by grpc servers
    _ = func(ctx context.Context) {
        // add a field to the context, this field will always be printed in the next
        // log calls with the context.
        ctxzap.AddFields(ctx, zap.String("data", "1"))

        // replace an existing field or append it to the context
        ctxzap.ReplaceField(ctx, zap.String("data", "2"))

        // print a log
        ctxzap.Info(ctx, "call with data", zap.String("value", "2"))
    }
}

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddFields

func AddFields(ctx context.Context, fields ...zap.Field)

AddFields attach more fields to the context

func Debug

func Debug(ctx context.Context, msg string, fields ...zap.Field)

Debug log

func Error

func Error(ctx context.Context, msg string, fields ...zap.Field)

Error log

func FromContext

func FromContext(ctx context.Context) *zap.Logger

FromContext extract logger from context Please use this with caution, this method will create a new logger, leveled logging functions like Info, Warn is preferred.

func Info

func Info(ctx context.Context, msg string, fields ...zap.Field)

Info log

func ReplaceField

func ReplaceField(ctx context.Context, field zap.Field)

ReplaceField replace existing field or append new field

func ToContext

func ToContext(ctx context.Context, logger *zap.Logger, fields []zap.Field) context.Context

ToContext put logger to context

func Warn

func Warn(ctx context.Context, msg string, fields ...zap.Field)

Warn log

Types

This section is empty.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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