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 ""

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 {

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


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.

Answered By – mfathirirhas

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.