Jake Muller
Jake Muller

Reputation: 1063

Zap logger source line

How to print the exact source line using zap. I create a package where it stores variable(zap logger). This global variable will be called inside functions in that package. The problem is it's not printing the actual caller, instead it calls where the logger called inside function inside the logger package. Here is my code:

package log

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

var logger        *zap.Logger

func Init() {
    logger,_ = zap.NewDevelopment()
}

func Info(msg interface{}) {
    if v,ok := msg.(string); ok {
        logger.Info(v) // when I called this function it always print the caller from this line, not the caller outside who actually called this function.
    } else {
        logger.Info(fmt.Sprintf("%v",msg))
    }
}

What's workaround to print value of source line for the actual caller?

Upvotes: 0

Views: 3180

Answers (2)

Sefa Şahin
Sefa Şahin

Reputation: 176

var (
    //APP_ENV for config
    APP_ENV = "APP_ENV"
)

func init() {
    BuildLogger(os.Getenv(APP_ENV))
}

// BuildLogger builds log config
func BuildLogger(env string) {
    var outputPaths []string
    var level zapcore.Level

    if env == "development" || env == "" {
        outputPaths = []string{"stdout"}
        level = zapcore.DebugLevel
    } else if env == "production" {
        outputPaths = setOutputPaths()
        level = zapcore.InfoLevel
    }

    config = zap.Config{
        Level:       zap.NewAtomicLevelAt(level),
        Development: false,
        Sampling: &zap.SamplingConfig{
            Initial:    100,
            Thereafter: 100,
        },
        Encoding:         "json",
        EncoderConfig:    zap.NewProductionEncoderConfig(),
        OutputPaths:      outputPaths,
        ErrorOutputPaths: []string{"stderr"},
    }

    logger, err := config.Build(zap.AddCallerSkip(1))
    if err != nil {
        panic(err)
    }

    log = logger.Sugar()
}

This is my logger configuration. Added logger, err := config.Build(zap.AddCallerSkip(1)) this line and worked, caller changed.

Upvotes: 1

mfathirirhas
mfathirirhas

Reputation: 2287

Use runtime caller.

import "runtime"

// call below line inside your Info function.
pc, src, line, ok := runtime.Caller(1)

src and line are what you need.

Upvotes: 2

Related Questions