Commit 5a01133e authored by Andrew Newdigate's avatar Andrew Newdigate 💬

Adds labkit logging package

Unlike some of the other functionality provided by Logkit,
the logging functionality does not wrap an underlying log provider.

Why not? Because, in a past life, I worked as a Java developer and
therefore understand that log wrappers will bring you nothing but pain
and unhappiness.

Instead of being a log wrapper, this functionality encourages
applications to use logrus. Logrus is already widely used in GitLab.

What benefit does this functionality add:
* Consistent configuration of logrus
* Importantly, this functionality allows labkit itself to write logs.
  * This will allow us to add better logging, as well as standardised
    access loggers, exception loggers etc
Co-authored-by: default avatarZeger-Jan van de Weg <zegerjan@gitlab.com>
parent 0159d973
......@@ -12,24 +12,19 @@
```go
import (
"gitlab.com/gitlab-org/labkit/correlation"
"gitlab.com/gitlab-org/labkit/correlation"
)
```
The main correlation package. Provides http middlewares for general purpose use cases:
### Logging
1. _Generating_ a correlation-id for an incoming HTTP request using
[**`InjectCorrelationID`**](https://godoc.org/gitlab.com/gitlab-org/labkit/correlation#InjectCorrelationID).
[Example](https://godoc.org/gitlab.com/gitlab-org/labkit/correlation#example-InjectCorrelationID)
1. _Obtaining_ the correlation-id from the context using
[**`ExtractFromContext`**](https://godoc.org/gitlab.com/gitlab-org/labkit/correlation#ExtractFromContext). [Example](https://godoc.org/gitlab.com/gitlab-org/labkit/correlation#example-ExtractFromContext--ForLogging)
1. _Injecting_ the correlation-id from the context into an outgoing request using
[**`NewInstrumentedRoundTripper`**](https://godoc.org/gitlab.com/gitlab-org/labkit/correlation#NewInstrumentedRoundTripper).
[Example](https://godoc.org/gitlab.com/gitlab-org/labkit/correlation#example-NewInstrumentedRoundTripper)
[![](https://godoc.org/gitlab.com/gitlab-org/labkit/log?status.svg)](http://godoc.org/gitlab.com/gitlab-org/labkit/log)
The following functionality is not yet implemented
1. TODO: _Extracting_ a correlation-id from an incoming HTTP request into the context
```go
import (
logkit "gitlab.com/gitlab-org/labkit/log"
)
```
## Developing LabKit
......
package correlation
const FieldName = "correlation_id"
......@@ -3,23 +3,25 @@ module gitlab.com/gitlab-org/labkit
require (
github.com/certifi/gocertifi v0.0.0-20180905225744-ee1a9a0726d2 // indirect
github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/getsentry/raven-go v0.1.0
github.com/gogo/protobuf v1.1.1 // indirect
github.com/grpc-ecosystem/go-grpc-middleware v1.0.0
github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect
github.com/lightstep/lightstep-tracer-go v0.15.6
github.com/onsi/ginkgo v1.7.0 // indirect
github.com/onsi/gomega v1.4.3 // indirect
github.com/opentracing/opentracing-go v1.0.2
github.com/philhofer/fwd v1.0.0 // indirect
github.com/pkg/errors v0.8.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/testify v1.2.2
github.com/sirupsen/logrus v1.3.0
github.com/stretchr/testify v1.3.0
github.com/tinylib/msgp v1.0.2 // indirect
github.com/uber-go/atomic v1.3.2 // indirect
github.com/uber/jaeger-client-go v2.15.0+incompatible
github.com/uber/jaeger-lib v1.5.0 // indirect
go.uber.org/atomic v1.3.2 // indirect
golang.org/x/crypto v0.0.0-20190228161510-8dd112bcdc25 // indirect
golang.org/x/sys v0.0.0-20190306220723-b294cbcfc56d // indirect
google.golang.org/grpc v1.16.0
gopkg.in/DataDog/dd-trace-go.v1 v1.7.0
)
......@@ -4,6 +4,7 @@ github.com/certifi/gocertifi v0.0.0-20180905225744-ee1a9a0726d2/go.mod h1:GJKEex
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd h1:qMd81Ts1T2OTKmB4acZcyKaMtRnY5Y44NuXGX2GFJ1w=
github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
......@@ -23,6 +24,10 @@ github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmg
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/konsorten/go-windows-terminal-sequences v1.0.2 h1:DB17ag19krx9CFsz4o3enTrPXyIXCl+2iCXH/aMAp9s=
github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/lightstep/lightstep-tracer-go v0.15.6 h1:D0GGa7afJ7GcQvu5as6ssLEEKYXvRgKI5d5cevtz8r4=
github.com/lightstep/lightstep-tracer-go v0.15.6/go.mod h1:6AMpwZpsyCFwSovxzM78e+AsYxE8sGwiM6C3TytaWeI=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
......@@ -38,8 +43,14 @@ github.com/pkg/errors v0.8.0 h1:WdK/asTD0HN+q6hsWO3/vpuAkAr+tw6aNJNDFFf0+qw=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.3.0 h1:hI/7Q+DtNZ2kINb6qt/lS+IyXnHQe9e90POfeewL/ME=
github.com/sirupsen/logrus v1.3.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/tinylib/msgp v1.0.2 h1:DfdQrzQa7Yh2es9SuLkixqxuXS2SxsdYn0KbdrOGWD8=
github.com/tinylib/msgp v1.0.2/go.mod h1:+d+yLhGm8mzTaHzB+wgMYrodPfmZrzkirds8fDWklFE=
github.com/uber-go/atomic v1.3.2 h1:Azu9lPBWRNKzYXSIwRfgRuDuS0YKsK4NFhiQv98gkxo=
......@@ -50,6 +61,10 @@ github.com/uber/jaeger-lib v1.5.0 h1:OHbgr8l656Ub3Fw5k9SWnBfIEwvoHQ+W2y+Aa9D1Uyo
github.com/uber/jaeger-lib v1.5.0/go.mod h1:ComeNDZlWwrWnDv8aPp0Ba6+uUTzImX/AauajbLI56U=
go.uber.org/atomic v1.3.2 h1:2Oa65PReHzfn29GpvgsYwloV9AVFHPDk8tYxt2c2tr4=
go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793 h1:u+LnwYTOOW7Ukr/fppxEb1Nwz0AtPflrblfvUudpo+I=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190228161510-8dd112bcdc25 h1:jsG6UpNLt9iAsb0S2AGW28DveNzzgmbXR+ENoPjUeIU=
golang.org/x/crypto v0.0.0-20190228161510-8dd112bcdc25/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d h1:g9qWBGx4puODJTMVyoPrpoxPFgVGd+z1DZwjfRu4d0I=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
......@@ -60,8 +75,12 @@ golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6Zh
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522 h1:Ve1ORMCxvRmSXBwJK+t3Oy+V2vRW2OetUQBq4rJIkZE=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e h1:o3PsSEY8E4eXWkXrIP9YJALUkVZqzHJT5DOasTyn8Vs=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190306220723-b294cbcfc56d h1:4Ew1XHJYjwX6RiE8SgSymqS1zCRQyGpcAnVfbpEuXfE=
golang.org/x/sys v0.0.0-20190306220723-b294cbcfc56d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
......
/*
Labkit uses Logrus for logging.
Applications that use Labkit should rely directly on Labkit.
This package provides some utility methods for working with Labkit, including:
1. Initialize Logrus in a consistent manner
1. Using GitLab's defaults with logrus
1. Passing correlation-ids between contexts and logrus
Please review the examples for more details of how to use this package.
*/
package logkit
package logkit_test
import (
log "github.com/sirupsen/logrus"
logkit "gitlab.com/gitlab-org/labkit/log"
)
func ExampleInitialize() {
// Initialize the global logger
closer, err := logkit.Initialize(
logkit.WithFormatter("json"), // Use JSON formatting
logkit.WithLogLevel("info"), // Use info level
logkit.WithOutputName("stderr"), // Output to stderr
)
defer closer.Close()
log.WithError(err).Info("This has been logged")
// Example of configuring a non-global logger using labkit
myLogger := log.New() // New logrus logger
closer2, err := logkit.Initialize(
logkit.WithLogger(myLogger), // Tell logkit to initialize myLogger
logkit.WithFormatter("text"), // Use text formatting
logkit.WithLogLevel("debug"), // Use debug level
logkit.WithOutputName("/var/log/labkit.log"), // Output to `/var/log/labkit.log`
)
defer closer2.Close()
myLogger.WithError(err).Info("This has been logged")
}
package logkit
import (
"io"
"os"
)
type nopCloser struct{}
func (nopCloser) Close() error { return nil }
// Initialize will configure the logger based on the options passed. It will
// validate the options and if validation fails drop to the defaults while
// logging a message to STDERR.
func Initialize(opts ...LoggerOption) (io.Closer, error) {
conf := applyLoggerOptions(opts)
// Being unable to open the output file will cause an error
writer, closer, err := getOutputWriter(conf)
if err != nil {
return closer, err
}
conf.logger.SetFormatter(conf.formatter)
conf.logger.SetLevel(conf.level)
conf.logger.SetOutput(writer)
// Only output the warnings _after_ the logger has been configured
for _, warning := range conf.warnings {
conf.logger.Warn(warning)
}
return closer, nil
}
func getOutputWriter(conf *loggerConfig) (io.Writer, io.Closer, error) {
if conf.writer != nil {
return conf.writer, nopCloser{}, nil
}
f, err := os.OpenFile(conf.outputPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
return f, nopCloser{}, err
}
return f, f, nil
}
package logkit
import (
"bytes"
"regexp"
"testing"
log "github.com/sirupsen/logrus"
"github.com/stretchr/testify/require"
)
func TestInitialize(t *testing.T) {
tests := []struct {
name string
opts []LoggerOption
wantErr bool
regexps []*regexp.Regexp
infoMessage string
debugMessage string
}{
{
name: "trivial",
regexps: []*regexp.Regexp{
regexp.MustCompile(`^$`),
},
},
{
name: "simple",
infoMessage: "Hello",
regexps: []*regexp.Regexp{
regexp.MustCompile(`^time=.*level=info.*msg=Hello`),
},
},
{
name: "simple-json",
opts: []LoggerOption{
WithFormatter("json"),
},
infoMessage: "Hello",
regexps: []*regexp.Regexp{
regexp.MustCompile(`^{"level":"info","msg":"Hello"`),
},
},
{
name: "simple-text",
opts: []LoggerOption{
WithFormatter("text"),
},
infoMessage: "Hello",
regexps: []*regexp.Regexp{
regexp.MustCompile(`^time=.*level=info.*msg=Hello`),
},
},
{
name: "invalid-formatter",
opts: []LoggerOption{
WithFormatter("rubbish"),
},
infoMessage: "Hello",
regexps: []*regexp.Regexp{
regexp.MustCompile(`^time=.*level=warning.*msg="unknown logging format rubbish, ignoring option"`),
regexp.MustCompile(`(?m)^time=.*level=info.*msg=Hello`),
},
},
{
name: "loglevel-below-threshold",
opts: []LoggerOption{
WithLogLevel("info"),
},
debugMessage: "Hello",
regexps: []*regexp.Regexp{
regexp.MustCompile(`^$`),
},
},
{
name: "loglevel-at-threshold",
opts: []LoggerOption{
WithLogLevel("info"),
},
infoMessage: "InfoHello",
debugMessage: "DebugHello",
regexps: []*regexp.Regexp{
regexp.MustCompile(`^time=.*level=info.*msg=InfoHello\n$`),
},
},
{
name: "invalid-threshold",
opts: []LoggerOption{
WithLogLevel("garbage"),
},
infoMessage: "InfoHello",
debugMessage: "DebugHello",
regexps: []*regexp.Regexp{
regexp.MustCompile(`level=warning msg="unknown log level, ignoring option`),
regexp.MustCompile(`(?m)^time=.*level=info.*msg=InfoHello\n$`),
},
},
{
name: "invalid-threshold-json-format",
opts: []LoggerOption{
WithFormatter("json"),
WithLogLevel("garbage"),
},
infoMessage: "InfoHello",
debugMessage: "DebugHello",
regexps: []*regexp.Regexp{
regexp.MustCompile(`"msg":"unknown log level, ignoring option: not a valid logrus Level`),
regexp.MustCompile(`"msg":"InfoHello"`),
},
},
{
name: "emit-to-stderr",
opts: []LoggerOption{
WithOutputName("stderr"),
},
infoMessage: "InfoHello",
regexps: []*regexp.Regexp{
regexp.MustCompile(`^time=.*level=info.*msg=InfoHello\n$`),
},
},
{
name: "emit-to-stdout",
opts: []LoggerOption{
WithOutputName("stdout"),
},
infoMessage: "InfoHello",
regexps: []*regexp.Regexp{
regexp.MustCompile(`^time=.*level=info.*msg=InfoHello\n$`),
},
},
{
name: "emit-to-file",
opts: []LoggerOption{
WithOutputName("/tmp/test.log"),
},
infoMessage: "InfoHello",
regexps: []*regexp.Regexp{
regexp.MustCompile(`^time=.*level=info.*msg=InfoHello\n$`),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var buf bytes.Buffer
opts := append([]LoggerOption{}, tt.opts...)
opts = append(opts, WithWriter(&buf))
closer, err := Initialize(opts...)
defer closer.Close()
if tt.infoMessage != "" {
log.Info(tt.infoMessage)
}
if tt.debugMessage != "" {
log.Debug(tt.debugMessage)
}
if tt.wantErr {
require.Error(t, err)
} else {
require.NoError(t, err)
}
bytes := buf.Bytes()
for _, re := range tt.regexps {
require.Regexp(t, re, string(bytes))
}
})
}
}
package logkit
import (
"context"
"os"
"github.com/sirupsen/logrus"
"gitlab.com/gitlab-org/labkit/correlation"
)
var logger = logrus.StandardLogger()
func init() {
// Enfore our own defaults on the logrus stdlogger
logger.Out = os.Stderr
logger.Formatter = &logrus.TextFormatter{}
logger.Level = logrus.InfoLevel
}
// ContextLogger will set the correlation id in the logger based on the context.
// This reference should not be held outside of the scope of the context
func ContextLogger(ctx context.Context) *logrus.Entry {
return logger.WithFields(ContextFields(ctx))
}
// ContextFields a logrus fields structure with the CorrelationID set
func ContextFields(ctx context.Context) logrus.Fields {
correlationID := correlation.ExtractFromContext(ctx)
return logrus.Fields{correlation.FieldName: correlationID}
}
package logkit
import (
"fmt"
"io"
"os"
"github.com/sirupsen/logrus"
)
type loggerConfig struct {
logger *logrus.Logger
level logrus.Level
formatter logrus.Formatter
outputPath string
writer io.Writer
// A list of warnings that will be emitted once the logger is configured
warnings []string
}
// LoggerOption will configure a new logrus Logger
type LoggerOption func(*loggerConfig)
func applyLoggerOptions(opts []LoggerOption) *loggerConfig {
conf := loggerConfig{
logger: logger,
level: logrus.InfoLevel,
formatter: &logrus.TextFormatter{},
writer: os.Stdout,
}
for _, v := range opts {
v(&conf)
}
return &conf
}
// WithFormatter allows setting the format to either `text` or `json`. In case
// the input is not recognized it defaults to text.
func WithFormatter(format string) LoggerOption {
return func(conf *loggerConfig) {
switch format {
case "text":
conf.formatter = &logrus.TextFormatter{}
case "json":
conf.formatter = &logrus.JSONFormatter{}
default:
conf.warnings = append(conf.warnings, fmt.Sprintf("unknown logging format %s, ignoring option", format))
}
}
}
// WithLogLevel is used to set the log level when defaulting to `info` is not
// wanted. Other options are: `debug`, `warn`, `error`, `fatal`, and `panic`.
func WithLogLevel(level string) LoggerOption {
return func(conf *loggerConfig) {
logrusLevel, err := logrus.ParseLevel(level)
if err != nil {
conf.warnings = append(conf.warnings, fmt.Sprintf("unknown log level, ignoring option: %v", err))
} else {
conf.level = logrusLevel
}
}
}
// WithOutputName allows customization of the sink of the logger. Output is either:
// `stdout`, `stderr`, or a path to a file.
func WithOutputName(outputName string) LoggerOption {
return func(conf *loggerConfig) {
switch outputName {
case "stdout":
conf.writer = os.Stdout
case "stderr":
conf.writer = os.Stderr
default:
conf.writer = nil
conf.outputPath = outputName
}
}
}
// WithWriter allows the writer to be customized. The application is responsible for closing the writer manually.
func WithWriter(writer io.Writer) LoggerOption {
return func(conf *loggerConfig) {
conf.writer = writer
}
}
// WithLogger allows you to configure a proprietary logger using the `Initialize` method
func WithLogger(logger *logrus.Logger) LoggerOption {
return func(conf *loggerConfig) {
conf.logger = logger
}
}
......@@ -7,8 +7,6 @@ import (
"gitlab.com/gitlab-org/labkit/correlation"
)
const keyCorrelationBaggageItem = "correlation_id"
// BaggageHandler will set opentracing baggage items with the current correlation_id
func BaggageHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
......@@ -17,11 +15,11 @@ func BaggageHandler(h http.Handler) http.Handler {
if span := opentracing.SpanFromContext(ctx); span != nil {
correlationID := correlation.ExtractFromContext(ctx)
if correlationID != "" {
span.SetBaggageItem(keyCorrelationBaggageItem, correlationID)
span.SetBaggageItem(correlation.FieldName, correlationID)
} else {
// If the span contains the correlation_id, but the context doesn't
// inject it from the span
correlationID = span.BaggageItem(keyCorrelationBaggageItem)
correlationID = span.BaggageItem(correlation.FieldName)
if correlationID != "" {
ctx = correlation.ContextWithCorrelation(ctx, correlationID)
r = r.WithContext(ctx)
......
......@@ -3,12 +3,12 @@ package tracing
import (
"context"
"fmt"
"log"
"os"
"sort"
opentracing "github.com/opentracing/opentracing-go"
"gitlab.com/gitlab-org/labkit/correlation"
logkit "gitlab.com/gitlab-org/labkit/log"
)
// envCorrelationIDKey is used to pass the current correlation-id over to the child process
......@@ -50,7 +50,7 @@ func NewEnvInjector(opts ...EnvInjectorOption) EnvInjector {
err := span.Tracer().Inject(span.Context(), opentracing.TextMap, carrier)
if err != nil {
log.Printf("tracing span injection failed: %v", err)
logkit.ContextLogger(ctx).WithError(err).Error("tracing span injection failed")
}
return appendMapToEnv(env, envMap)
......
......@@ -4,11 +4,11 @@ import (
"context"
"fmt"
"io"
"log"
"net/http"
"os/exec"
"time"
log "github.com/sirupsen/logrus"
"gitlab.com/gitlab-org/labkit/tracing"
)
......@@ -79,7 +79,7 @@ func ExampleNewEnvInjector() {
cmd.Env = envInjector(context.Background(), env)
if err := cmd.Run(); err != nil {
log.Fatal(err)
log.WithError(err).Fatal("Command failed")
}
}
......
......@@ -5,10 +5,10 @@ package impl
import (
"fmt"
"io"
"log"
"strconv"
opentracing "github.com/opentracing/opentracing-go"
log "github.com/sirupsen/logrus"
jaegercfg "github.com/uber/jaeger-client-go/config"
jaegerlog "github.com/uber/jaeger-client-go/log"
)
......
......@@ -6,10 +6,10 @@ import (
"context"
"fmt"
"io"
"log"
lightstep "github.com/lightstep/lightstep-tracer-go"
opentracing "github.com/opentracing/opentracing-go"
log "github.com/sirupsen/logrus"
)