newrelic / go-agent

New Relic Go Agent
Apache License 2.0
762 stars 297 forks source link

Feat: automatically reference transaction from context on slog #880

Closed adomaskizogian closed 4 months ago

adomaskizogian commented 4 months ago

I would like to introduce a handler that takes new relic transaction data from context automatically.

It is quite a common pattern to inject the base slog logger instance to some piece of code only so to pass it to nrslog.WithContext to receive a handler that captures logs in context. I find this api to be a bit leaky and introducing noise. Especially that slog already has methods which make context available for handlers.

With introduction of this handler one now can set a slog instance relying on a NRHandler as default one and call it from anywhere, ensuring that log calls with be passed to go-agent, as well as if the context contains transaction it will be linked. This is quite the case for http services which rely on newrelic.WrapHandle

an example:

on main.go

app, _ := newrelic.NewApplication(
  newrelic.ConfigAppName("foo"),
  newrelic.ConfigLicense("bar"),
)

instrumentedHandler := nrslog.WithTransactionFromContext(nrslog.TextHandler(app, os.Stderr, &slog.HandlerOptions{}))
slog.SetDefault(slog.New(instrumentedHandler))

on service.go

func DoSomeWork(ctx context.Context, app *newrelic.Application){
  txn := app.StartTransaction("baz")
  defer txn.End()

  ctx = newrelic.NewContext(ctx, txn)

  slog.InfoContext(ctx, "qux")  
}

All feedback is welcome. The implementation itself was hacked out pretty quick. I am open for suggestions for taking a different approach such as re-implementing the handler. At the moment this new feature is implemented using a decorator which disables setting the transactions externally and only allows passing transaction via context.

I hope this will serve as a good starting point for a discussion.

btw, not sure if the tests will pass as I found no way to run tests on local env.

CLAassistant commented 4 months ago

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
2 out of 3 committers have signed the CLA.

:white_check_mark: iamemilio
:white_check_mark: nr-swilloughby
:x: adomaskizogian
You have signed the CLA already but the status is still pending? Let us recheck it.