Note: This documentation uses v2 of the Go tracer, which Datadog recommends for all users. If you are using v1, see the migration guide to upgrade to v2.

Manual injection

The Go tracer API allows printing span information along with log statements using the %v format specifier:

package main

import (
    "net/http"

    "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer" // 1.x
    // "github.com/DataDog/dd-trace-go/v2/ddtrace/tracer" // 2.x
)

func handler(w http.ResponseWriter, r *http.Request) {
    // Create a span for a web request at the /posts URL.
    span := tracer.StartSpan("web.request", tracer.ResourceName("/posts"))
    defer span.Finish()

    // Append span info to log messages:
    log.Printf("my log message %v", span)
}

The above example illustrates how to use the span’s context in the standard library’s log package. Similar logic may be applied to third party packages too.

Note: If you are not using a Datadog Log Integration to parse your logs, custom log parsing rules need to ensure that dd.trace_id, dd.span_id, dd.service, dd.env and dd.version are being parsed as strings. More information can be found in Correlated Logs Not Showing Up in the Trace ID Panel.

Injection into logrus logs

A hook for the logrus package is available to automatically link your log and spans.

package main

import (
    "github.com/sirupsen/logrus"

    dd_logrus "gopkg.in/DataDog/dd-trace-go.v1/contrib/sirupsen/logrus" // 1.x
    "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer" // 1.x
    // dd_logrus "github.com/DataDog/dd-trace-go/contrib/sirupsen/logrus/v2" // 2.x
    // "github.com/DataDog/dd-trace-go/v2/ddtrace/tracer" // 2.x
)

func main() {
    // Optional: Change log format to use JSON (Cf. Go Log Collection)
    logrus.SetFormatter(&logrus.JSONFormatter{})

    // Add Datadog context log hook
    logrus.AddHook(&dd_logrus.DDContextLogHook{}) 
    
    // ...
}

This automatically injects the trace id to your logs when you log with the context.

    // Log with the context
    logrus.WithContext(ctx).Info("Go logs and traces connected!")

Further Reading

PREVIEWING: hannahkm/clarify-v2-docs