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

How to get function name in log output ? #925

Open
ganeshskudva opened this issue Mar 1, 2021 · 1 comment
Open

How to get function name in log output ? #925

ganeshskudva opened this issue Mar 1, 2021 · 1 comment

Comments

@ganeshskudva
Copy link

How to get function name printed in logs ? I see this PR request has added this functionality. I am unable to get it working though

This is my code:

package main

import (
	"go.uber.org/zap"
)

var logger *zap.Logger

func main() {
	logger := NewLogger()
	logger.Info("Test msg Main")
	TestFunc(logger)
}

func TestFunc(logger *zap.Logger)  {
	logger.Info("Test msg TestFunc")
}

func NewLogger() *zap.Logger {
	config := zap.NewDevelopmentConfig()
	opts := []zap.Option{
		zap.AddCallerSkip(1), // traverse call depth for more useful log lines
		zap.AddCaller(),
	}

	logger, _ = config.Build(opts...)
	return logger
}

This is the output I get with/without the addition of AddCaller() option

2021-03-01T15:00:02.927-0800    INFO    runtime/proc.go:204     Test msg Main
2021-03-01T15:00:02.927-0800    INFO    cmd/main.go:12  Test msg TestFunc

I am expecting something like

2021-03-01T15:00:02.927-0800    INFO    runtime/proc.go:204   main  Test msg Main
2021-03-01T15:00:02.927-0800    INFO    cmd/main.go:12  TestFunc Test msg TestFunc](url)
@prashantv
Copy link
Collaborator

You need to set the FunctionKey field in the EncoderConfig, e.g.,

	config := zap.NewDevelopmentConfig()
	config.EncoderConfig.FunctionKey = "func"

That should include a field called "func" which will contain the caller's function name.

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

No branches or pull requests

2 participants