Skip to content
New issue

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

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

Already on GitHub? # to your account

Dynamic Fields With Defer #95

Open
ahshah opened this issue Jan 19, 2021 · 1 comment
Open

Dynamic Fields With Defer #95

ahshah opened this issue Jan 19, 2021 · 1 comment

Comments

@ahshah
Copy link

ahshah commented Jan 19, 2021

Hi folks,
I'd like to add a field to my logging context after I have some relevant information, I've supplied the peudocode of what I'd like to do. Looking over the code in log/entry.go, this should be pretty straightforward, however it seems like a conscience decision to not allow modification to the Entry structs field variable. Instead, similar functions (i.e WithField) require the building of a new Entry entirely.
Why is the Entry struct immutable in this way?

func DownloadFile() (int) { 
   // Off to the network we go
}
func main() {
      ctx := log.WithFields(log.Fields{
          "module": "main",
     })
     defer ctx.Info("Download complete")
     bytesDownloaded := DownloadFile()
     ctx.AddField("downloadSize", bytesDownloaded)
}
@tj
Copy link
Member

tj commented Jan 22, 2021

It was meant to be more of a functional API, which I suppose is mostly a personal preference. You should be fine to do:

defer func(){
  ctx.WithField("downloadSize", ...).Info("Download complete")
}()

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

No branches or pull requests

2 participants