grpc-ecosystem / go-grpc-middleware

Golang gRPC Middlewares: interceptor chaining, auth, logging, retries and more.
Apache License 2.0
6.29k stars 693 forks source link

logging.InjectFields does not work. #701

Open taeungshin opened 7 months ago

taeungshin commented 7 months ago

logging.InjectFields does not work.

// It works. // grpc_ctxtags.Extract(ctx).Set("grpc.request.test", in.GetMessage())

// Doesn't work. ctx = logging.InjectFields(ctx, logging.Fields {"grpc.request.test", in.GetMessage()})

Can you give me more details on how to use this?

cgarm commented 7 months ago

Usage examples. A simple usage example:

package main

import (
    "context"
    "fmt"
    "log"
    "os"

    "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
)

func main() {
    l := log.New(os.Stderr, "", log.Ldate|log.Ltime|log.Lshortfile)
    logger := logging.LoggerFunc(func(_ context.Context, lvl logging.Level, msg string, fields ...any) {
        switch lvl {
        case logging.LevelDebug:
            msg = fmt.Sprintf("DEBUG :%v", msg)
        case logging.LevelInfo:
            msg = fmt.Sprintf("INFO :%v", msg)
        case logging.LevelWarn:
            msg = fmt.Sprintf("WARN :%v", msg)
        case logging.LevelError:
            msg = fmt.Sprintf("ERROR :%v", msg)
        default:
            panic(fmt.Sprintf("unknown level %v", lvl))
        }
        l.Println(append([]any{"msg", msg}, fields...))
    })

    ctx := context.Background()
    newCtx := logging.InjectFields(ctx, logging.Fields{"grpc.request.test", "abc"})
    logger.Log(newCtx, logging.LevelDebug, "Hello world!", logging.ExtractFields(newCtx)...)
}