Skip to content

alternative library for "New Relic Logs in Context" with log/slog.

License

Notifications You must be signed in to change notification settings

miyamo2/altnrslog

Repository files navigation

altnrslog

Go Reference GitHub go.mod Go version (subdirectory of monorepo) GitHub release (latest by date) codecov Go Report Card GitHub License

altnrslog is an alternative library for New Relic Logs in Context with log/slog.

altnrslog can also forward slog.Attr even only APM Agent.

Roadmap to release stable version

  • Transaction Scope
    • Supports Logs in Context with APM Agent
    • Supports Logs in Context without APM Agent
  • Application Scope CANCELED #32
    • Supports Logs in Context with APM Agent
    • Supports Logs in Context without APM Agent

Getting started

Installation

go get github.com/miyamo2/altnrslog

Simple Usage

package main

import (
	"encoding/json"
	"fmt"
	"github.com/miyamo2/altnrslog"
	"github.com/newrelic/go-agent/v3/newrelic"
	"log"
	"log/slog"
	"net/http"
	"os"
)

type IntroduceRequest struct {
	Name string `json:"name"`
}

func main() {
	nr, err := newrelic.NewApplication(
		newrelic.ConfigAppName(os.Getenv("NEW_RELIC_CONFIG_APP_NAME")),
		newrelic.ConfigLicense(os.Getenv("NEW_RELIC_CONFIG_LICENSE")),
		newrelic.ConfigAppLogForwardingEnabled(true),
	)
	if err != nil {
		panic(err)
	}

	http.HandleFunc(newrelic.WrapHandleFunc(nr, "/introduce", func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		tx := newrelic.FromContext(ctx)
		logHandler := altnrslog.NewTransactionalHandler(nr, tx)
		logger := slog.New(logHandler)

		var req IntroduceRequest
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}

		logger.InfoContext(ctx, "START", slog.Group("request", slog.String("name", req.Name)))

		response := fmt.Sprintf("Hello, %s!", req.Name)
		defer logger.InfoContext(ctx, "END", slog.String("response", response))

		w.Write([]byte(response))
	}))

	log.Fatal(http.ListenAndServe(":8080", nil))
}

Contributing

Feel free to open PR or an Issue.

About

alternative library for "New Relic Logs in Context" with log/slog.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages