Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

logging.InjectFields does not work. #701

Open
taeungshin opened this issue Apr 5, 2024 · 1 comment
Open

logging.InjectFields does not work. #701

taeungshin opened this issue Apr 5, 2024 · 1 comment

Comments

@taeungshin
Copy link

taeungshin commented Apr 5, 2024

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?

@taeungshin taeungshin changed the title logging.ExtractFields does not work. logging.InjectFields does not work. Apr 5, 2024
@cgarm
Copy link

cgarm commented Apr 7, 2024

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)...)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants