Skip to content

Instantly share code, notes, and snippets.

@malisetti
Created March 2, 2023 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malisetti/f1aeaeab92e16675325d1da1182f951d to your computer and use it in GitHub Desktop.
Save malisetti/f1aeaeab92e16675325d1da1182f951d to your computer and use it in GitHub Desktop.
correlating datadog logs and apm with chi trace and logrus packages in a http server
package main
import (
"net/http"
// "os"
"time"
chitrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/go-chi/chi.v5"
ddlogrus "gopkg.in/DataDog/dd-trace-go.v1/contrib/sirupsen/logrus"
"github.com/go-chi/chi/v5"
"github.com/sirupsen/logrus"
)
func main() {
// Ensure your tracer is started and stopped
// Setup logrus, do this once at the beginning of your program
// logrus.SetFormatter(&logrus.JSONFormatter{})
// hook takes the tracing info from a context and updates log fields
logrus.AddHook(&ddlogrus.DDContextLogHook{})
// logrus.SetOutput(os.Stdout)
// span, sctx := tracer.StartSpanFromContext(context.Background(), "mySpan")
// defer span.Finish()
router := chi.NewRouter()
// chitrace middleware injects trace info to request context
router.Use(chitrace.Middleware(chitrace.WithAnalytics(true), chitrace.WithServiceName("chi.router")))
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Pass the current span context to the logger (Time is set for consistency in output here)
cLog := logrus.WithContext(r.Context()).WithTime(time.Date(2000, 1, 1, 1, 1, 1, 0, time.UTC))
// Log as desired using the context-aware logger
cLog.Info("Completed some work!")
// Output:
// {"dd.span_id":0,"dd.trace_id":0,"level":"info","msg":"Completed some work!","time":"2000-01-01T01:01:01Z"}
})
http.ListenAndServe(":8081", router)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment