diff --git a/contrib/IBM/sarama.v1/sarama.go b/contrib/IBM/sarama.v1/sarama.go index 7d9f86701e..ef879b0228 100644 --- a/contrib/IBM/sarama.v1/sarama.go +++ b/contrib/IBM/sarama.v1/sarama.go @@ -47,7 +47,7 @@ func WrapPartitionConsumer(pc sarama.PartitionConsumer, opts ...Option) sarama.P for _, opt := range opts { opt(cfg) } - log.Debug("contrib/IBM/sarama: Wrapping Partition Consumer: %#v", cfg) + log.Debugf("contrib/IBM/sarama: Wrapping Partition Consumer: %#v", cfg) wrapped := &partitionConsumer{ PartitionConsumer: pc, messages: make(chan *sarama.ConsumerMessage), @@ -170,7 +170,7 @@ func WrapSyncProducer(saramaConfig *sarama.Config, producer sarama.SyncProducer, for _, opt := range opts { opt(cfg) } - log.Debug("contrib/IBM/sarama: Wrapping Sync Producer: %#v", cfg) + log.Debugf("contrib/IBM/sarama: Wrapping Sync Producer: %#v", cfg) if saramaConfig == nil { saramaConfig = sarama.NewConfig() } @@ -214,7 +214,7 @@ func WrapAsyncProducer(saramaConfig *sarama.Config, p sarama.AsyncProducer, opts for _, opt := range opts { opt(cfg) } - log.Debug("contrib/IBM/sarama: Wrapping Async Producer: %#v", cfg) + log.Debugf("contrib/IBM/sarama: Wrapping Async Producer: %#v", cfg) if saramaConfig == nil { saramaConfig = sarama.NewConfig() saramaConfig.Version = sarama.V0_11_0_0 diff --git a/contrib/Shopify/sarama/sarama.go b/contrib/Shopify/sarama/sarama.go index 5b96be10a7..6c3a8c6d71 100644 --- a/contrib/Shopify/sarama/sarama.go +++ b/contrib/Shopify/sarama/sarama.go @@ -50,7 +50,7 @@ func WrapPartitionConsumer(pc sarama.PartitionConsumer, opts ...Option) sarama.P for _, opt := range opts { opt(cfg) } - log.Debug("contrib/Shopify/sarama: Wrapping Partition Consumer: %#v", cfg) + log.Debugf("contrib/Shopify/sarama: Wrapping Partition Consumer: %#v", cfg) wrapped := &partitionConsumer{ PartitionConsumer: pc, messages: make(chan *sarama.ConsumerMessage), @@ -173,7 +173,7 @@ func WrapSyncProducer(saramaConfig *sarama.Config, producer sarama.SyncProducer, for _, opt := range opts { opt(cfg) } - log.Debug("contrib/Shopify/sarama: Wrapping Sync Producer: %#v", cfg) + log.Debugf("contrib/Shopify/sarama: Wrapping Sync Producer: %#v", cfg) if saramaConfig == nil { saramaConfig = sarama.NewConfig() } @@ -217,7 +217,7 @@ func WrapAsyncProducer(saramaConfig *sarama.Config, p sarama.AsyncProducer, opts for _, opt := range opts { opt(cfg) } - log.Debug("contrib/Shopify/sarama: Wrapping Async Producer: %#v", cfg) + log.Debugf("contrib/Shopify/sarama: Wrapping Async Producer: %#v", cfg) if saramaConfig == nil { saramaConfig = sarama.NewConfig() saramaConfig.Version = sarama.V0_11_0_0 diff --git a/contrib/aws/aws-sdk-go-v2/aws/aws.go b/contrib/aws/aws-sdk-go-v2/aws/aws.go index 4509f55bfc..105abc7960 100644 --- a/contrib/aws/aws-sdk-go-v2/aws/aws.go +++ b/contrib/aws/aws-sdk-go-v2/aws/aws.go @@ -101,7 +101,7 @@ func (mw *traceMiddleware) startTraceMiddleware(stack *middleware.Stack) error { } k, v, err := resourceNameFromParams(in, serviceID) if err != nil { - log.Debug("Error: %v", err) + log.Debugf("Error: %v", err) } else { opts = append(opts, tracer.Tag(k, v)) } diff --git a/contrib/aws/aws-sdk-go/aws/aws.go b/contrib/aws/aws-sdk-go/aws/aws.go index 93d60a9824..e194435b27 100644 --- a/contrib/aws/aws-sdk-go/aws/aws.go +++ b/contrib/aws/aws-sdk-go/aws/aws.go @@ -57,7 +57,7 @@ func WrapSession(s *session.Session, opts ...Option) *session.Session { for _, opt := range opts { opt(cfg) } - log.Debug("contrib/aws/aws-sdk-go/aws: Wrapping Session: %#v", cfg) + log.Debugf("contrib/aws/aws-sdk-go/aws: Wrapping Session: %#v", cfg) h := &handlers{cfg: cfg} s = s.Copy() s.Handlers.Send.PushFrontNamed(request.NamedHandler{ @@ -183,7 +183,7 @@ func extraTagsForService(req *request.Request) map[string]interface{} { return nil } if err != nil { - log.Debug("failed to extract tags for AWS service %q: %v", service, err) + log.Debugf("failed to extract tags for AWS service %q: %v", service, err) return nil } return extraTags diff --git a/contrib/aws/internal/eventbridge/eventbridge.go b/contrib/aws/internal/eventbridge/eventbridge.go index 5a2a56068e..7beb7e44e4 100644 --- a/contrib/aws/internal/eventbridge/eventbridge.go +++ b/contrib/aws/internal/eventbridge/eventbridge.go @@ -8,14 +8,15 @@ package eventbridge import ( "encoding/json" "fmt" + "strconv" + "time" + "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/eventbridge" "github.com/aws/aws-sdk-go-v2/service/eventbridge/types" "github.com/aws/smithy-go/middleware" "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer" "gopkg.in/DataDog/dd-trace-go.v1/internal/log" - "strconv" - "time" ) const ( @@ -43,7 +44,7 @@ func handlePutEvents(span tracer.Span, in middleware.InitializeInput) { carrier := tracer.TextMapCarrier{} err := tracer.Inject(span.Context(), carrier) if err != nil { - log.Debug("Unable to inject trace context: %s", err) + log.Debugf("Unable to inject trace context: %s", err) return } @@ -53,7 +54,7 @@ func handlePutEvents(span tracer.Span, in middleware.InitializeInput) { carrierJSON, err := json.Marshal(carrier) if err != nil { - log.Debug("Unable to marshal trace context: %s", err) + log.Debugf("Unable to marshal trace context: %s", err) return } diff --git a/contrib/aws/internal/sfn/sfn.go b/contrib/aws/internal/sfn/sfn.go index bafe1a89e6..73a039673a 100644 --- a/contrib/aws/internal/sfn/sfn.go +++ b/contrib/aws/internal/sfn/sfn.go @@ -52,13 +52,13 @@ func injectTraceContext(span tracer.Span, input *string) *string { } traceCtxCarrier := tracer.TextMapCarrier{} if err := tracer.Inject(span.Context(), traceCtxCarrier); err != nil { - log.Debug("Unable to inject trace context: %s", err) + log.Debugf("Unable to inject trace context: %s", err) return input } traceCtxJSON, err := json.Marshal(traceCtxCarrier) if err != nil { - log.Debug("Unable to marshal trace context: %s", err) + log.Debugf("Unable to marshal trace context: %s", err) return input } diff --git a/contrib/aws/internal/sns/sns.go b/contrib/aws/internal/sns/sns.go index b40ca5ea85..68e1b13dff 100644 --- a/contrib/aws/internal/sns/sns.go +++ b/contrib/aws/internal/sns/sns.go @@ -7,6 +7,7 @@ package sns import ( "encoding/json" + "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sns" "github.com/aws/aws-sdk-go-v2/service/sns/types" @@ -32,13 +33,13 @@ func EnrichOperation(span tracer.Span, in middleware.InitializeInput, operation func handlePublish(span tracer.Span, in middleware.InitializeInput) { params, ok := in.Parameters.(*sns.PublishInput) if !ok { - log.Debug("Unable to read PublishInput params") + log.Debugf("Unable to read PublishInput params") return } traceContext, err := getTraceContext(span) if err != nil { - log.Debug("Unable to get trace context: %s", err.Error()) + log.Debugf("Unable to get trace context: %s", err.Error()) return } @@ -58,7 +59,7 @@ func handlePublishBatch(span tracer.Span, in middleware.InitializeInput) { traceContext, err := getTraceContext(span) if err != nil { - log.Debug("Unable to get trace context: %s", err.Error()) + log.Debugf("Unable to get trace context: %s", err.Error()) return } diff --git a/contrib/aws/internal/sqs/sqs.go b/contrib/aws/internal/sqs/sqs.go index 9fbd8a9f90..fcbf9271e2 100644 --- a/contrib/aws/internal/sqs/sqs.go +++ b/contrib/aws/internal/sqs/sqs.go @@ -7,6 +7,7 @@ package sqs import ( "encoding/json" + "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sqs" "github.com/aws/aws-sdk-go-v2/service/sqs/types" @@ -38,7 +39,7 @@ func handleSendMessage(span tracer.Span, in middleware.InitializeInput) { traceContext, err := getTraceContext(span) if err != nil { - log.Debug("Unable to get trace context: %s", err.Error()) + log.Debugf("Unable to get trace context: %s", err.Error()) return } @@ -58,7 +59,7 @@ func handleSendMessageBatch(span tracer.Span, in middleware.InitializeInput) { traceContext, err := getTraceContext(span) if err != nil { - log.Debug("Unable to get trace context: %s", err.Error()) + log.Debugf("Unable to get trace context: %s", err.Error()) return } diff --git a/contrib/bradfitz/gomemcache/memcache/memcache.go b/contrib/bradfitz/gomemcache/memcache/memcache.go index 106a9255f3..719247f403 100644 --- a/contrib/bradfitz/gomemcache/memcache/memcache.go +++ b/contrib/bradfitz/gomemcache/memcache/memcache.go @@ -39,7 +39,7 @@ func WrapClient(client *memcache.Client, opts ...ClientOption) *Client { for _, opt := range opts { opt(cfg) } - log.Debug("contrib/bradfitz/gomemcache/memcache: Wrapping Client: %#v", cfg) + log.Debugf("contrib/bradfitz/gomemcache/memcache: Wrapping Client: %#v", cfg) return &Client{ Client: client, cfg: cfg, diff --git a/contrib/cloud.google.com/go/pubsub.v1/internal/tracing/tracing.go b/contrib/cloud.google.com/go/pubsub.v1/internal/tracing/tracing.go index 43633fbf48..7948db1a59 100644 --- a/contrib/cloud.google.com/go/pubsub.v1/internal/tracing/tracing.go +++ b/contrib/cloud.google.com/go/pubsub.v1/internal/tracing/tracing.go @@ -77,7 +77,7 @@ func TracePublish(ctx context.Context, topic Topic, msg *Message, opts ...Option msg.Attributes = make(map[string]string) } if err := tracer.Inject(span.Context(), tracer.TextMapCarrier(msg.Attributes)); err != nil { - log.Debug("contrib/cloud.google.com/go/pubsub.v1/trace: failed injecting tracing attributes: %v", err) + log.Debugf("contrib/cloud.google.com/go/pubsub.v1/trace: failed injecting tracing attributes: %v", err) } span.SetTag("num_attributes", len(msg.Attributes)) @@ -96,7 +96,7 @@ func TraceReceiveFunc(s Subscription, opts ...Option) func(ctx context.Context, for _, opt := range opts { opt(cfg) } - log.Debug("contrib/cloud.google.com/go/pubsub.v1/trace: Wrapping Receive Handler: %#v", cfg) + log.Debugf("contrib/cloud.google.com/go/pubsub.v1/trace: Wrapping Receive Handler: %#v", cfg) return func(ctx context.Context, msg *Message) (context.Context, func()) { parentSpanCtx, _ := tracer.Extract(tracer.TextMapCarrier(msg.Attributes)) opts := []ddtrace.StartSpanOption{ diff --git a/contrib/confluentinc/confluent-kafka-go/kafka.v2/kafka.go b/contrib/confluentinc/confluent-kafka-go/kafka.v2/kafka.go index 24bbe5a3d8..caa9952aa4 100644 --- a/contrib/confluentinc/confluent-kafka-go/kafka.v2/kafka.go +++ b/contrib/confluentinc/confluent-kafka-go/kafka.v2/kafka.go @@ -65,7 +65,7 @@ func WrapConsumer(c *kafka.Consumer, opts ...Option) *Consumer { Consumer: c, tracer: newKafkaTracer(opts...), } - log.Debug("%s: Wrapping Consumer: %#v", logPrefix, wrapped.tracer) + log.Debugf("%s: Wrapping Consumer: %#v", logPrefix, wrapped.tracer) wrapped.events = tracing.WrapConsumeEventsChannel(wrapped.tracer, c.Events(), c, wrapEvent) return wrapped } @@ -168,7 +168,7 @@ func WrapProducer(p *kafka.Producer, opts ...Option) *Producer { tracer: newKafkaTracer(opts...), events: p.Events(), } - log.Debug("%s: Wrapping Producer: %#v", logPrefix, wrapped.tracer) + log.Debugf("%s: Wrapping Producer: %#v", logPrefix, wrapped.tracer) wrapped.produceChannel = tracing.WrapProduceChannel(wrapped.tracer, p.ProduceChannel(), wrapMessage) if wrapped.tracer.DSMEnabled() { wrapped.events = tracing.WrapProduceEventsChannel(wrapped.tracer, p.Events(), wrapEvent) diff --git a/contrib/confluentinc/confluent-kafka-go/kafka/kafka.go b/contrib/confluentinc/confluent-kafka-go/kafka/kafka.go index b4f5485c37..e8c1f1918e 100644 --- a/contrib/confluentinc/confluent-kafka-go/kafka/kafka.go +++ b/contrib/confluentinc/confluent-kafka-go/kafka/kafka.go @@ -65,7 +65,7 @@ func WrapConsumer(c *kafka.Consumer, opts ...Option) *Consumer { Consumer: c, tracer: newKafkaTracer(opts...), } - log.Debug("%s: Wrapping Consumer: %#v", logPrefix, wrapped.tracer) + log.Debugf("%s: Wrapping Consumer: %#v", logPrefix, wrapped.tracer) wrapped.events = tracing.WrapConsumeEventsChannel(wrapped.tracer, c.Events(), c, wrapEvent) return wrapped } @@ -168,7 +168,7 @@ func WrapProducer(p *kafka.Producer, opts ...Option) *Producer { tracer: newKafkaTracer(opts...), events: p.Events(), } - log.Debug("%s: Wrapping Producer: %#v", logPrefix, wrapped.tracer) + log.Debugf("%s: Wrapping Producer: %#v", logPrefix, wrapped.tracer) wrapped.produceChannel = tracing.WrapProduceChannel(wrapped.tracer, p.ProduceChannel(), wrapMessage) if wrapped.tracer.DSMEnabled() { wrapped.events = tracing.WrapProduceEventsChannel(wrapped.tracer, p.Events(), wrapEvent) diff --git a/contrib/database/sql/conn.go b/contrib/database/sql/conn.go index 91cadea451..42a9f56db3 100644 --- a/contrib/database/sql/conn.go +++ b/contrib/database/sql/conn.go @@ -300,7 +300,7 @@ func (tc *TracedConn) injectComments(ctx context.Context, query string, mode tra carrier := tracer.SQLCommentCarrier{Query: query, Mode: mode, DBServiceName: tc.cfg.serviceName, PeerDBHostname: tc.meta[ext.TargetHost], PeerDBName: tc.meta[ext.DBName], PeerService: tc.providedPeerService(ctx)} if err := carrier.Inject(spanCtx); err != nil { // this should never happen - log.Warn("contrib/database/sql: failed to inject query comments: %v", err) + log.Warnf("contrib/database/sql: failed to inject query comments: %v", err) } return carrier.Query, carrier.SpanID } diff --git a/contrib/database/sql/internal/dsn.go b/contrib/database/sql/internal/dsn.go index 9d9eee9d40..153f4cdf46 100644 --- a/contrib/database/sql/internal/dsn.go +++ b/contrib/database/sql/internal/dsn.go @@ -21,19 +21,19 @@ func ParseDSN(driverName, dsn string) (meta map[string]string, err error) { case "mysql": meta, err = parseMySQLDSN(dsn) if err != nil { - log.Debug("Error parsing DSN for mysql: %v", err) + log.Debugf("Error parsing DSN for mysql: %v", err) return } case "postgres", "pgx": meta, err = parsePostgresDSN(dsn) if err != nil { - log.Debug("Error parsing DSN for postgres: %v", err) + log.Debugf("Error parsing DSN for postgres: %v", err) return } case "sqlserver": meta, err = parseSQLServerDSN(dsn) if err != nil { - log.Debug("Error parsing DSN for sqlserver: %v", err) + log.Debugf("Error parsing DSN for sqlserver: %v", err) return } default: @@ -41,7 +41,7 @@ func ParseDSN(driverName, dsn string) (meta map[string]string, err error) { u, e := url.Parse(dsn) if e != nil { // dsn is not a valid URL, so just ignore - log.Debug("Error parsing driver name from DSN: %v", e) + log.Debugf("Error parsing driver name from DSN: %v", e) return } if driverName != u.Scheme { diff --git a/contrib/database/sql/metrics.go b/contrib/database/sql/metrics.go index d8ff4ed266..17f525242a 100644 --- a/contrib/database/sql/metrics.go +++ b/contrib/database/sql/metrics.go @@ -34,7 +34,7 @@ var interval = 10 * time.Second // pollDBStats calls (*DB).Stats on the db at a predetermined interval. It pushes the DBStats off to the statsd client. // the caller should always ensure that db & statsd are non-nil func pollDBStats(statsd internal.StatsdClient, db *sql.DB) { - log.Debug("DB stats will be gathered and sent every %v.", interval) + log.Debugf("DB stats will be gathered and sent every %v.", interval) for range time.NewTicker(interval).C { log.Debug("Reporting DB.Stats metrics...") stat := db.Stats() diff --git a/contrib/database/sql/option.go b/contrib/database/sql/option.go index 567c861cb8..18865ca7f7 100644 --- a/contrib/database/sql/option.go +++ b/contrib/database/sql/option.go @@ -43,9 +43,9 @@ func (c *config) checkStatsdRequired() { sc, err := internal.NewStatsdClient(globalconfig.DogstatsdAddr(), statsTags(c)) if err == nil { c.statsdClient = sc - log.Debug("Metrics from the database/sql contrib will be sent to %v", globalconfig.DogstatsdAddr()) + log.Debugf("Metrics from the database/sql contrib will be sent to %v", globalconfig.DogstatsdAddr()) } else { - log.Warn("Error creating statsd client for database/sql contrib; DB Stats disabled: %v", err) + log.Warnf("Error creating statsd client for database/sql contrib; DB Stats disabled: %v", err) c.dbStats = false } } @@ -57,7 +57,7 @@ func (c *config) checkDBMPropagation(driverName string, driver driver.Driver, ds dsn = c.dsn } if dbSystem, ok := dbmFullModeUnsupported(driverName, driver, dsn); ok { - log.Warn("Using DBM_PROPAGATION_MODE in 'full' mode is not supported for %s, downgrading to 'service' mode. "+ + log.Warnf("Using DBM_PROPAGATION_MODE in 'full' mode is not supported for %s, downgrading to 'service' mode. "+ "See https://docs.datadoghq.com/database_monitoring/connect_dbm_and_apm/ for more info.", dbSystem, ) diff --git a/contrib/database/sql/sql.go b/contrib/database/sql/sql.go index b26318d0d3..6c18215b25 100644 --- a/contrib/database/sql/sql.go +++ b/contrib/database/sql/sql.go @@ -124,7 +124,7 @@ func Register(driverName string, driver driver.Driver, opts ...RegisterOption) { cfg := new(config) defaults(cfg, driverName, nil) processOptions(cfg, driverName, driver, "", opts...) - log.Debug("contrib/database/sql: Registering driver: %s %#v", driverName, cfg) + log.Debugf("contrib/database/sql: Registering driver: %s %#v", driverName, cfg) registeredDrivers.add(driverName, driver, cfg) } diff --git a/contrib/dimfeld/httptreemux.v5/httptreemux.go b/contrib/dimfeld/httptreemux.v5/httptreemux.go index e50c951cb9..abe57334e0 100644 --- a/contrib/dimfeld/httptreemux.v5/httptreemux.go +++ b/contrib/dimfeld/httptreemux.v5/httptreemux.go @@ -42,7 +42,7 @@ func New(opts ...RouterOption) *Router { cfg.spanOpts = append(cfg.spanOpts, tracer.Measured()) cfg.spanOpts = append(cfg.spanOpts, tracer.Tag(ext.SpanKind, ext.SpanKindServer)) cfg.spanOpts = append(cfg.spanOpts, tracer.Tag(ext.Component, componentName)) - log.Debug("contrib/dimfeld/httptreemux.v5: Configuring Router: %#v", cfg) + log.Debugf("contrib/dimfeld/httptreemux.v5: Configuring Router: %#v", cfg) return &Router{httptreemux.New(), cfg} } @@ -77,7 +77,7 @@ func NewWithContext(opts ...RouterOption) *ContextRouter { cfg.spanOpts = append(cfg.spanOpts, tracer.Measured()) cfg.spanOpts = append(cfg.spanOpts, tracer.Tag(ext.SpanKind, ext.SpanKindServer)) cfg.spanOpts = append(cfg.spanOpts, tracer.Tag(ext.Component, componentName)) - log.Debug("contrib/dimfeld/httptreemux.v5: Configuring ContextRouter: %#v", cfg) + log.Debugf("contrib/dimfeld/httptreemux.v5: Configuring ContextRouter: %#v", cfg) return &ContextRouter{httptreemux.NewContextMux(), cfg} } diff --git a/contrib/emicklei/go-restful.v3/restful.go b/contrib/emicklei/go-restful.v3/restful.go index 10fa7dce4e..38c4194b7d 100644 --- a/contrib/emicklei/go-restful.v3/restful.go +++ b/contrib/emicklei/go-restful.v3/restful.go @@ -32,7 +32,7 @@ func FilterFunc(configOpts ...Option) restful.FilterFunction { for _, opt := range configOpts { opt(cfg) } - log.Debug("contrib/emicklei/go-restful/v3: Creating tracing filter: %#v", cfg) + log.Debugf("contrib/emicklei/go-restful/v3: Creating tracing filter: %#v", cfg) spanOpts := []ddtrace.StartSpanOption{tracer.ServiceName(cfg.serviceName)} return func(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { spanOpts := append( diff --git a/contrib/emicklei/go-restful/restful.go b/contrib/emicklei/go-restful/restful.go index 8dc6ff6fc2..59bc203840 100644 --- a/contrib/emicklei/go-restful/restful.go +++ b/contrib/emicklei/go-restful/restful.go @@ -35,7 +35,7 @@ func FilterFunc(configOpts ...Option) restful.FilterFunction { for _, opt := range configOpts { opt(cfg) } - log.Debug("contrib/emicklei/go-restful: Creating tracing filter: %#v", cfg) + log.Debugf("contrib/emicklei/go-restful: Creating tracing filter: %#v", cfg) spanOpts := []ddtrace.StartSpanOption{tracer.ServiceName(cfg.serviceName)} return func(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { spanOpts := append(spanOpts, tracer.ResourceName(req.SelectedRoutePath())) diff --git a/contrib/garyburd/redigo/redigo.go b/contrib/garyburd/redigo/redigo.go index c3326fa2ed..d4c91941dd 100644 --- a/contrib/garyburd/redigo/redigo.go +++ b/contrib/garyburd/redigo/redigo.go @@ -67,7 +67,7 @@ func parseOptions(options ...interface{}) ([]redis.DialOption, *dialConfig) { // The set of supported options must be either of type redis.DialOption or this package's DialOption. func Dial(network, address string, options ...interface{}) (redis.Conn, error) { dialOpts, cfg := parseOptions(options...) - log.Debug("contrib/garyburd/redigo: Dialing %s %s, %#v", network, address, cfg) + log.Debugf("contrib/garyburd/redigo: Dialing %s %s, %#v", network, address, cfg) c, err := redis.Dial(network, address, dialOpts...) if err != nil { return nil, err @@ -86,7 +86,7 @@ func Dial(network, address string, options ...interface{}) (redis.Conn, error) { // The returned redis.Conn is traced. func DialURL(rawurl string, options ...interface{}) (redis.Conn, error) { dialOpts, cfg := parseOptions(options...) - log.Debug("contrib/garyburd/redigo: Dialing %s, %#v", rawurl, cfg) + log.Debugf("contrib/garyburd/redigo: Dialing %s, %#v", rawurl, cfg) u, err := url.Parse(rawurl) if err != nil { return Conn{}, err diff --git a/contrib/gin-gonic/gin/gintrace.go b/contrib/gin-gonic/gin/gintrace.go index 7a36dc1522..2b301ad93e 100644 --- a/contrib/gin-gonic/gin/gintrace.go +++ b/contrib/gin-gonic/gin/gintrace.go @@ -35,7 +35,7 @@ func Middleware(service string, opts ...Option) gin.HandlerFunc { for _, opt := range opts { opt(cfg) } - log.Debug("contrib/gin-gonic/gin: Configuring Middleware: Service: %s, %#v", cfg.serviceName, cfg) + log.Debugf("contrib/gin-gonic/gin: Configuring Middleware: Service: %s, %#v", cfg.serviceName, cfg) spanOpts := []tracer.StartSpanOption{ tracer.ServiceName(cfg.serviceName), tracer.Tag(ext.Component, componentName), diff --git a/contrib/globalsign/mgo/mgo.go b/contrib/globalsign/mgo/mgo.go index 8d46ff6bd1..5dd79585c5 100644 --- a/contrib/globalsign/mgo/mgo.go +++ b/contrib/globalsign/mgo/mgo.go @@ -62,7 +62,7 @@ func Dial(url string, opts ...DialOption) (*Session, error) { for _, fn := range opts { fn(s.cfg) } - log.Debug("contrib/globalsign/mgo: Dialing: %s, %#v", url, s.cfg) + log.Debugf("contrib/globalsign/mgo: Dialing: %s, %#v", url, s.cfg) return s, err } diff --git a/contrib/go-chi/chi.v5/chi.go b/contrib/go-chi/chi.v5/chi.go index 73706d9765..f313d868f1 100644 --- a/contrib/go-chi/chi.v5/chi.go +++ b/contrib/go-chi/chi.v5/chi.go @@ -36,7 +36,7 @@ func Middleware(opts ...Option) func(next http.Handler) http.Handler { for _, fn := range opts { fn(cfg) } - log.Debug("contrib/go-chi/chi.v5: Configuring Middleware: %#v", cfg) + log.Debugf("contrib/go-chi/chi.v5: Configuring Middleware: %#v", cfg) spanOpts := append(cfg.spanOpts, tracer.ServiceName(cfg.serviceName), tracer.Tag(ext.Component, componentName), tracer.Tag(ext.SpanKind, ext.SpanKindServer)) diff --git a/contrib/go-chi/chi/chi.go b/contrib/go-chi/chi/chi.go index 1a5c2791c4..5280caac2a 100644 --- a/contrib/go-chi/chi/chi.go +++ b/contrib/go-chi/chi/chi.go @@ -36,7 +36,7 @@ func Middleware(opts ...Option) func(next http.Handler) http.Handler { for _, fn := range opts { fn(cfg) } - log.Debug("contrib/go-chi/chi: Configuring Middleware: %#v", cfg) + log.Debugf("contrib/go-chi/chi: Configuring Middleware: %#v", cfg) spanOpts := append(cfg.spanOpts, tracer.ServiceName(cfg.serviceName), tracer.Tag(ext.Component, componentName), tracer.Tag(ext.SpanKind, ext.SpanKindServer)) diff --git a/contrib/go-redis/redis/redis.go b/contrib/go-redis/redis/redis.go index 56feb6dcfd..cd2b2ad8bf 100644 --- a/contrib/go-redis/redis/redis.go +++ b/contrib/go-redis/redis/redis.go @@ -73,7 +73,7 @@ func WrapClient(c *redis.Client, opts ...ClientOption) *Client { for _, fn := range opts { fn(cfg) } - log.Debug("contrib/go-redis/redis: Wrapping Client: %#v", cfg) + log.Debugf("contrib/go-redis/redis: Wrapping Client: %#v", cfg) opt := c.Options() host, port, err := net.SplitHostPort(opt.Addr) if err != nil { diff --git a/contrib/go.mongodb.org/mongo-driver/mongo/mongo.go b/contrib/go.mongodb.org/mongo-driver/mongo/mongo.go index c8332874ca..8c043f2944 100644 --- a/contrib/go.mongodb.org/mongo-driver/mongo/mongo.go +++ b/contrib/go.mongodb.org/mongo-driver/mongo/mongo.go @@ -106,7 +106,7 @@ func NewMonitor(opts ...Option) *event.CommandMonitor { for _, opt := range opts { opt(cfg) } - log.Debug("contrib/go.mongodb.org/mongo-driver/mongo: Creating Monitor: %#v", cfg) + log.Debugf("contrib/go.mongodb.org/mongo-driver/mongo: Creating Monitor: %#v", cfg) m := &monitor{ spans: make(map[spanKey]ddtrace.Span), cfg: cfg, diff --git a/contrib/gocql/gocql/gocql.go b/contrib/gocql/gocql/gocql.go index 058c557109..361f01fda0 100644 --- a/contrib/gocql/gocql/gocql.go +++ b/contrib/gocql/gocql/gocql.go @@ -153,7 +153,7 @@ func wrapQuery(q *gocql.Query, hosts []string, opts ...WrapOption) *Query { if len(hosts) > 0 { p.clusterContactPoints = strings.Join(hosts, ",") } - log.Debug("contrib/gocql/gocql: Wrapping Query: %#v", cfg) + log.Debugf("contrib/gocql/gocql: Wrapping Query: %#v", cfg) tq := &Query{Query: q, params: p, ctx: q.Context()} return tq } @@ -318,7 +318,7 @@ func wrapBatch(b *gocql.Batch, hosts []string, opts ...WrapOption) *Batch { if len(hosts) > 0 { p.clusterContactPoints = strings.Join(hosts, ",") } - log.Debug("contrib/gocql/gocql: Wrapping Batch: %#v", cfg) + log.Debugf("contrib/gocql/gocql: Wrapping Batch: %#v", cfg) tb := &Batch{Batch: b, params: p, ctx: b.Context()} return tb } diff --git a/contrib/gocql/gocql/option.go b/contrib/gocql/gocql/option.go index e6e70a75e4..ea481054d5 100644 --- a/contrib/gocql/gocql/option.go +++ b/contrib/gocql/gocql/option.go @@ -51,7 +51,7 @@ func defaultConfig() *config { if semver.IsValid(compatMode) { cfg.clusterTagLegacyMode = semver.Compare(semver.MajorMinor(compatMode), "v1.65") <= 0 } else { - log.Warn("ignoring DD_TRACE_GOCQL_COMPAT: invalid version %q", compatMode) + log.Warnf("ignoring DD_TRACE_GOCQL_COMPAT: invalid version %q", compatMode) } } cfg.errCheck = func(error) bool { return true } diff --git a/contrib/gofiber/fiber.v2/fiber.go b/contrib/gofiber/fiber.v2/fiber.go index 7d9ef223fe..4181354290 100644 --- a/contrib/gofiber/fiber.v2/fiber.go +++ b/contrib/gofiber/fiber.v2/fiber.go @@ -35,7 +35,7 @@ func Middleware(opts ...Option) func(c *fiber.Ctx) error { for _, fn := range opts { fn(cfg) } - log.Debug("gofiber/fiber.v2: Middleware: %#v", cfg) + log.Debugf("gofiber/fiber.v2: Middleware: %#v", cfg) return func(c *fiber.Ctx) error { if cfg.ignoreRequest(c) { return c.Next() diff --git a/contrib/gomodule/redigo/redigo.go b/contrib/gomodule/redigo/redigo.go index dfabb11bfd..907bf16e98 100644 --- a/contrib/gomodule/redigo/redigo.go +++ b/contrib/gomodule/redigo/redigo.go @@ -97,7 +97,7 @@ func wrapConn(c redis.Conn, p *params) redis.Conn { // The set of supported options must be either of type redis.DialOption or this package's DialOption. func Dial(network, address string, options ...interface{}) (redis.Conn, error) { dialOpts, cfg := parseOptions(options...) - log.Debug("contrib/gomodule/redigo: Dialing %s %s, %#v", network, address, cfg) + log.Debugf("contrib/gomodule/redigo: Dialing %s %s, %#v", network, address, cfg) c, err := redis.Dial(network, address, dialOpts...) if err != nil { return nil, err @@ -114,7 +114,7 @@ func Dial(network, address string, options ...interface{}) (redis.Conn, error) { // The set of supported options must be either of type redis.DialOption or this package's DialOption. func DialContext(ctx context.Context, network, address string, options ...interface{}) (redis.Conn, error) { dialOpts, cfg := parseOptions(options...) - log.Debug("contrib/gomodule/redigo: Dialing with context %s %s, %#v", network, address, cfg) + log.Debugf("contrib/gomodule/redigo: Dialing with context %s %s, %#v", network, address, cfg) c, err := redis.DialContext(ctx, network, address, dialOpts...) if err != nil { return nil, err @@ -133,7 +133,7 @@ func DialContext(ctx context.Context, network, address string, options ...interf // The returned redis.Conn is traced. func DialURL(rawurl string, options ...interface{}) (redis.Conn, error) { dialOpts, cfg := parseOptions(options...) - log.Debug("contrib/gomodule/redigo: Dialing %s, %#v", rawurl, cfg) + log.Debugf("contrib/gomodule/redigo: Dialing %s, %#v", rawurl, cfg) u, err := url.Parse(rawurl) if err != nil { return Conn{}, err diff --git a/contrib/google.golang.org/api/api.go b/contrib/google.golang.org/api/api.go index a8bf163f0a..7b6d4f7244 100644 --- a/contrib/google.golang.org/api/api.go +++ b/contrib/google.golang.org/api/api.go @@ -58,12 +58,12 @@ func loadEndpointsFromJSON() ([]*tree.Endpoint, error) { func initAPIEndpointsTree() { apiEndpoints, err := loadEndpointsFromJSON() if err != nil { - log.Warn("contrib/google.golang.org/api: failed load json endpoints: %v", err) + log.Warnf("contrib/google.golang.org/api: failed load json endpoints: %v", err) return } tr, err := tree.New(apiEndpoints...) if err != nil { - log.Warn("contrib/google.golang.org/api: failed to create endpoints tree: %v", err) + log.Warnf("contrib/google.golang.org/api: failed to create endpoints tree: %v", err) return } apiEndpointsTree = tr @@ -73,7 +73,7 @@ func initAPIEndpointsTree() { // APIs with all requests traced automatically. func NewClient(options ...Option) (*http.Client, error) { cfg := newConfig(options...) - log.Debug("contrib/google.golang.org/api: Creating Client: %#v", cfg) + log.Debugf("contrib/google.golang.org/api: Creating Client: %#v", cfg) client, err := google.DefaultClient(cfg.ctx, cfg.scopes...) if err != nil { return nil, err @@ -86,7 +86,7 @@ func NewClient(options ...Option) (*http.Client, error) { // Google APIs and traces all requests. func WrapRoundTripper(transport http.RoundTripper, options ...Option) http.RoundTripper { cfg := newConfig(options...) - log.Debug("contrib/google.golang.org/api: Wrapping RoundTripper: %#v", cfg) + log.Debugf("contrib/google.golang.org/api: Wrapping RoundTripper: %#v", cfg) rtOpts := []httptrace.RoundTripperOption{ httptrace.WithBefore(func(req *http.Request, span ddtrace.Span) { if !cfg.endpointMetadataDisabled { diff --git a/contrib/google.golang.org/api/internal/tree/tree.go b/contrib/google.golang.org/api/internal/tree/tree.go index c6536b3e57..0770aed7bf 100644 --- a/contrib/google.golang.org/api/internal/tree/tree.go +++ b/contrib/google.golang.org/api/internal/tree/tree.go @@ -87,7 +87,7 @@ func (t *Tree) Get(hostname string, httpMethod string, httpPath string) (*Endpoi if e.pathMatcher == nil { pathMatcher, err := regexp.Compile(e.PathRegex) if err != nil { - log.Warn("contrib/google.golang.org/api: failed to create regex: %s: %v", e.PathRegex, err) + log.Warnf("contrib/google.golang.org/api: failed to create regex: %s: %v", e.PathRegex, err) continue } e.pathMatcher = pathMatcher diff --git a/contrib/google.golang.org/grpc/client.go b/contrib/google.golang.org/grpc/client.go index 78046f10d9..2fdf4243fa 100644 --- a/contrib/google.golang.org/grpc/client.go +++ b/contrib/google.golang.org/grpc/client.go @@ -78,7 +78,7 @@ func StreamClientInterceptor(opts ...Option) grpc.StreamClientInterceptor { for _, fn := range opts { fn(cfg) } - log.Debug("contrib/google.golang.org/grpc: Configuring StreamClientInterceptor: %#v", cfg) + log.Debugf("contrib/google.golang.org/grpc: Configuring StreamClientInterceptor: %#v", cfg) return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { var methodKind string if desc != nil { @@ -149,7 +149,7 @@ func UnaryClientInterceptor(opts ...Option) grpc.UnaryClientInterceptor { for _, fn := range opts { fn(cfg) } - log.Debug("contrib/google.golang.org/grpc: Configuring UnaryClientInterceptor: %#v", cfg) + log.Debugf("contrib/google.golang.org/grpc: Configuring UnaryClientInterceptor: %#v", cfg) return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { if _, ok := cfg.untracedMethods[method]; ok { return invoker(ctx, method, req, reply, cc, opts...) diff --git a/contrib/google.golang.org/grpc/server.go b/contrib/google.golang.org/grpc/server.go index a751e1a3a6..2eb86614da 100644 --- a/contrib/google.golang.org/grpc/server.go +++ b/contrib/google.golang.org/grpc/server.go @@ -86,7 +86,7 @@ func StreamServerInterceptor(opts ...Option) grpc.StreamServerInterceptor { for _, fn := range opts { fn(cfg) } - log.Debug("contrib/google.golang.org/grpc: Configuring StreamServerInterceptor: %#v", cfg) + log.Debugf("contrib/google.golang.org/grpc: Configuring StreamServerInterceptor: %#v", cfg) return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) { ctx := ss.Context() // if we've enabled call tracing, create a span @@ -135,7 +135,7 @@ func UnaryServerInterceptor(opts ...Option) grpc.UnaryServerInterceptor { for _, fn := range opts { fn(cfg) } - log.Debug("contrib/google.golang.org/grpc: Configuring UnaryServerInterceptor: %#v", cfg) + log.Debugf("contrib/google.golang.org/grpc: Configuring UnaryServerInterceptor: %#v", cfg) return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { _, im := cfg.ignoredMethods[info.FullMethod] _, um := cfg.untracedMethods[info.FullMethod] diff --git a/contrib/gopkg.in/jinzhu/gorm.v1/gorm.go b/contrib/gopkg.in/jinzhu/gorm.v1/gorm.go index dd5580e9a7..831c4ade93 100644 --- a/contrib/gopkg.in/jinzhu/gorm.v1/gorm.go +++ b/contrib/gopkg.in/jinzhu/gorm.v1/gorm.go @@ -80,7 +80,7 @@ func WithCallbacks(db *gorm.DB, opts ...Option) *gorm.DB { for _, fn := range opts { fn(cfg) } - log.Debug("contrib/gopkg.in/jinzhu/gorm.v1: Registering Callbacks: %#v", cfg) + log.Debugf("contrib/gopkg.in/jinzhu/gorm.v1: Registering Callbacks: %#v", cfg) return db.Set(gormConfigKey, cfg) } diff --git a/contrib/gorilla/mux/mux.go b/contrib/gorilla/mux/mux.go index 22affde4c9..e765a0cfe0 100644 --- a/contrib/gorilla/mux/mux.go +++ b/contrib/gorilla/mux/mux.go @@ -126,7 +126,7 @@ func WrapRouter(router *mux.Router, opts ...RouterOption) *Router { cfg := newConfig(opts) cfg.spanOpts = append(cfg.spanOpts, tracer.Tag(ext.Component, componentName)) cfg.spanOpts = append(cfg.spanOpts, tracer.Tag(ext.SpanKind, ext.SpanKindServer)) - log.Debug("contrib/gorilla/mux: Configuring Router: %#v", cfg) + log.Debugf("contrib/gorilla/mux: Configuring Router: %#v", cfg) return &Router{ Router: router, config: cfg, diff --git a/contrib/gorm.io/gorm.v1/gorm.go b/contrib/gorm.io/gorm.v1/gorm.go index b87b8b79a0..0df3f54e62 100644 --- a/contrib/gorm.io/gorm.v1/gorm.go +++ b/contrib/gorm.io/gorm.v1/gorm.go @@ -73,7 +73,7 @@ func withCallbacks(db *gorm.DB, opts ...Option) (*gorm.DB, error) { for _, fn := range opts { fn(cfg) } - log.Debug("Registering Callbacks: %#v", cfg) + log.Debugf("Registering Callbacks: %#v", cfg) afterFunc := func() func(*gorm.DB) { return func(db *gorm.DB) { diff --git a/contrib/graph-gophers/graphql-go/graphql.go b/contrib/graph-gophers/graphql-go/graphql.go index 040e7dff04..d1b2c19f23 100644 --- a/contrib/graph-gophers/graphql-go/graphql.go +++ b/contrib/graph-gophers/graphql-go/graphql.go @@ -145,7 +145,7 @@ func NewTracer(opts ...Option) tracer.Tracer { for _, opt := range opts { opt(cfg) } - log.Debug("contrib/graph-gophers/graphql-go: Configuring Graphql Tracer: %#v", cfg) + log.Debugf("contrib/graph-gophers/graphql-go: Configuring Graphql Tracer: %#v", cfg) return &Tracer{ cfg: cfg, } diff --git a/contrib/hashicorp/consul/consul.go b/contrib/hashicorp/consul/consul.go index 4182156eaa..4b861d6890 100644 --- a/contrib/hashicorp/consul/consul.go +++ b/contrib/hashicorp/consul/consul.go @@ -50,7 +50,7 @@ func WrapClient(c *consul.Client, opts ...ClientOption) *Client { for _, fn := range opts { fn(cfg) } - log.Debug("contrib/hashicorp/consul: Wrapping Client: %#v", cfg) + log.Debugf("contrib/hashicorp/consul: Wrapping Client: %#v", cfg) return &Client{c, cfg, context.Background()} } diff --git a/contrib/internal/httptrace/config.go b/contrib/internal/httptrace/config.go index 57d9a05c98..aeda72e58c 100644 --- a/contrib/internal/httptrace/config.go +++ b/contrib/internal/httptrace/config.go @@ -58,11 +58,11 @@ func newConfig() config { return c } else if s == "" { c.queryStringRegexp = nil - log.Debug("%s is set but empty. Query string obfuscation will be disabled.", envQueryStringRegexp) + log.Debugf("%s is set but empty. Query string obfuscation will be disabled.", envQueryStringRegexp) } else if r, err := regexp.Compile(s); err == nil { c.queryStringRegexp = r } else { - log.Error("Could not compile regexp from %s. Using default regexp instead.", envQueryStringRegexp) + log.Errorf("Could not compile regexp from %s. Using default regexp instead.", envQueryStringRegexp) } return c } @@ -88,24 +88,24 @@ func GetErrorCodesFromInput(s string) func(statusCode int) bool { if strings.Contains(val, "-") { bounds := strings.Split(val, "-") if len(bounds) != 2 { - log.Debug("Trouble parsing %v due to entry %v, using default error status determination logic", s, val) + log.Debugf("Trouble parsing %v due to entry %v, using default error status determination logic", s, val) return nil } before, err := strconv.Atoi(bounds[0]) if err != nil { - log.Debug("Trouble parsing %v due to entry %v, using default error status determination logic", s, val) + log.Debugf("Trouble parsing %v due to entry %v, using default error status determination logic", s, val) return nil } after, err := strconv.Atoi(bounds[1]) if err != nil { - log.Debug("Trouble parsing %v due to entry %v, using default error status determination logic", s, val) + log.Debugf("Trouble parsing %v due to entry %v, using default error status determination logic", s, val) return nil } ranges = append(ranges, []int{before, after}) } else { intVal, err := strconv.Atoi(val) if err != nil { - log.Debug("Trouble parsing %v due to entry %v, using default error status determination logic", s, val) + log.Debugf("Trouble parsing %v due to entry %v, using default error status determination logic", s, val) return nil } codes = append(codes, intVal) diff --git a/contrib/jackc/pgx.v5/metrics.go b/contrib/jackc/pgx.v5/metrics.go index eb94c50bfc..8ea5412281 100644 --- a/contrib/jackc/pgx.v5/metrics.go +++ b/contrib/jackc/pgx.v5/metrics.go @@ -35,7 +35,7 @@ var interval = 10 * time.Second // pollPoolStats calls (*pgxpool).Stats on the pool at a predetermined interval. It pushes the pool Stats off to the statsd client. func pollPoolStats(statsd internal.StatsdClient, pool *pgxpool.Pool) { - log.Debug("contrib/jackc/pgx.v5: Traced pool connection found: Pool stats will be gathered and sent every %v.", interval) + log.Debugf("contrib/jackc/pgx.v5: Traced pool connection found: Pool stats will be gathered and sent every %v.", interval) for range time.NewTicker(interval).C { log.Debug("contrib/jackc/pgx.v5: Reporting pgxpool.Stat metrics...") stat := pool.Stat() diff --git a/contrib/jackc/pgx.v5/option.go b/contrib/jackc/pgx.v5/option.go index b89a3968a0..96dd0bafaa 100644 --- a/contrib/jackc/pgx.v5/option.go +++ b/contrib/jackc/pgx.v5/option.go @@ -46,7 +46,7 @@ func (c *config) checkStatsdRequired() { if err == nil { c.statsdClient = sc } else { - log.Warn("contrib/jackc/pgx.v5: Error creating statsd client; Pool stats will be dropped: %v", err) + log.Warnf("contrib/jackc/pgx.v5: Error creating statsd client; Pool stats will be dropped: %v", err) } } } diff --git a/contrib/jinzhu/gorm/gorm.go b/contrib/jinzhu/gorm/gorm.go index 35d9c0f177..52233f9240 100644 --- a/contrib/jinzhu/gorm/gorm.go +++ b/contrib/jinzhu/gorm/gorm.go @@ -80,7 +80,7 @@ func WithCallbacks(db *gorm.DB, opts ...Option) *gorm.DB { for _, fn := range opts { fn(cfg) } - log.Debug("contrib/jinzhu/gorm: Adding Callbacks: %#v", cfg) + log.Debugf("contrib/jinzhu/gorm: Adding Callbacks: %#v", cfg) return db.Set(gormConfigKey, cfg) } diff --git a/contrib/julienschmidt/httprouter/httprouter.go b/contrib/julienschmidt/httprouter/httprouter.go index cffaa28876..0d430fca71 100644 --- a/contrib/julienschmidt/httprouter/httprouter.go +++ b/contrib/julienschmidt/httprouter/httprouter.go @@ -24,7 +24,7 @@ type Router struct { // New returns a new router augmented with tracing. func New(opts ...RouterOption) *Router { cfg := tracing.NewConfig(opts...) - log.Debug("contrib/julienschmidt/httprouter: Configuring Router: %#v", cfg) + log.Debugf("contrib/julienschmidt/httprouter: Configuring Router: %#v", cfg) return &Router{httprouter.New(), cfg} } diff --git a/contrib/labstack/echo.v4/echotrace.go b/contrib/labstack/echo.v4/echotrace.go index d3a8867bd4..567cadd35d 100644 --- a/contrib/labstack/echo.v4/echotrace.go +++ b/contrib/labstack/echo.v4/echotrace.go @@ -38,7 +38,7 @@ func Middleware(opts ...Option) echo.MiddlewareFunc { for _, fn := range opts { fn(cfg) } - log.Debug("contrib/labstack/echo.v4: Configuring Middleware: %#v", cfg) + log.Debugf("contrib/labstack/echo.v4: Configuring Middleware: %#v", cfg) spanOpts := make([]ddtrace.StartSpanOption, 0, 3+len(cfg.tags)) spanOpts = append(spanOpts, tracer.ServiceName(cfg.serviceName)) for k, v := range cfg.tags { diff --git a/contrib/labstack/echo/echotrace.go b/contrib/labstack/echo/echotrace.go index f1f7f063de..a8fd072edb 100644 --- a/contrib/labstack/echo/echotrace.go +++ b/contrib/labstack/echo/echotrace.go @@ -41,7 +41,7 @@ func Middleware(opts ...Option) echo.MiddlewareFunc { for _, fn := range opts { fn(cfg) } - log.Debug("contrib/labstack/echo: Configuring Middleware: %#v", cfg) + log.Debugf("contrib/labstack/echo: Configuring Middleware: %#v", cfg) spanOpts := []ddtrace.StartSpanOption{ tracer.ServiceName(cfg.serviceName), tracer.Tag(ext.Component, componentName), diff --git a/contrib/net/http/http.go b/contrib/net/http/http.go index 5aedb032a4..f2eabf7dbe 100644 --- a/contrib/net/http/http.go +++ b/contrib/net/http/http.go @@ -33,7 +33,7 @@ func NewServeMux(opts ...Option) *ServeMux { } cfg.spanOpts = append(cfg.spanOpts, tracer.Tag(ext.SpanKind, ext.SpanKindServer)) cfg.spanOpts = append(cfg.spanOpts, tracer.Tag(ext.Component, componentName)) - log.Debug("contrib/net/http: Configuring ServeMux: %#v", cfg) + log.Debugf("contrib/net/http: Configuring ServeMux: %#v", cfg) return &ServeMux{ ServeMux: http.NewServeMux(), cfg: cfg, @@ -90,7 +90,7 @@ func WrapHandler(h http.Handler, service, resource string, opts ...Option) http. } cfg.spanOpts = append(cfg.spanOpts, tracer.Tag(ext.SpanKind, ext.SpanKindServer)) cfg.spanOpts = append(cfg.spanOpts, tracer.Tag(ext.Component, componentName)) - log.Debug("contrib/net/http: Wrapping Handler: Service: %s, Resource: %s, %#v", service, resource, cfg) + log.Debugf("contrib/net/http: Wrapping Handler: Service: %s, Resource: %s, %#v", service, resource, cfg) return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { if cfg.ignoreRequest(req) { h.ServeHTTP(w, req) diff --git a/contrib/olivere/elastic/elastictrace.go b/contrib/olivere/elastic/elastictrace.go index a5440dc5db..e05b317da8 100644 --- a/contrib/olivere/elastic/elastictrace.go +++ b/contrib/olivere/elastic/elastictrace.go @@ -40,7 +40,7 @@ func NewHTTPClient(opts ...ClientOption) *http.Client { for _, fn := range opts { fn(cfg) } - log.Debug("contrib/olivere/elastic: Configuring HTTP Client: %#v", cfg) + log.Debugf("contrib/olivere/elastic: Configuring HTTP Client: %#v", cfg) return &http.Client{Transport: &httpTransport{config: cfg}} } diff --git a/contrib/segmentio/kafka.go.v0/internal/tracing/tracing.go b/contrib/segmentio/kafka.go.v0/internal/tracing/tracing.go index 9b5f7bbb9b..0fa9c5d052 100644 --- a/contrib/segmentio/kafka.go.v0/internal/tracing/tracing.go +++ b/contrib/segmentio/kafka.go.v0/internal/tracing/tracing.go @@ -54,7 +54,7 @@ func (tr *Tracer) StartConsumeSpan(ctx context.Context, msg Message) ddtrace.Spa span, _ := tracer.StartSpanFromContext(ctx, tr.consumerSpanName, opts...) // reinject the span context so consumers can pick it up if err := tracer.Inject(span.Context(), carrier); err != nil { - log.Debug("contrib/segmentio/kafka.go.v0: Failed to inject span context into carrier in reader, %v", err) + log.Debugf("contrib/segmentio/kafka.go.v0: Failed to inject span context into carrier in reader, %v", err) } return span } @@ -80,7 +80,7 @@ func (tr *Tracer) StartProduceSpan(ctx context.Context, writer Writer, msg Messa carrier := NewMessageCarrier(msg) span, _ := tracer.StartSpanFromContext(ctx, tr.producerSpanName, opts...) if err := tracer.Inject(span.Context(), carrier); err != nil { - log.Debug("contrib/segmentio/kafka.go.v0: Failed to inject span context into carrier in writer, %v", err) + log.Debugf("contrib/segmentio/kafka.go.v0: Failed to inject span context into carrier in writer, %v", err) } return span } diff --git a/contrib/segmentio/kafka.go.v0/kafka.go b/contrib/segmentio/kafka.go.v0/kafka.go index 93af2643af..ce7b9aad09 100644 --- a/contrib/segmentio/kafka.go.v0/kafka.go +++ b/contrib/segmentio/kafka.go.v0/kafka.go @@ -42,7 +42,7 @@ func WrapReader(c *kafka.Reader, opts ...Option) *Reader { kafkaCfg.ConsumerGroupID = c.Config().GroupID } wrapped.tracer = tracing.NewTracer(kafkaCfg, opts...) - log.Debug("contrib/segmentio/kafka-go.v0/kafka: Wrapping Reader: %#v", wrapped.tracer) + log.Debugf("contrib/segmentio/kafka-go.v0/kafka: Wrapping Reader: %#v", wrapped.tracer) return wrapped } @@ -110,7 +110,7 @@ func WrapWriter(w *kafka.Writer, opts ...Option) *Writer { kafkaCfg.BootstrapServers = w.Addr.String() } writer.tracer = tracing.NewTracer(kafkaCfg, opts...) - log.Debug("contrib/segmentio/kafka.go.v0: Wrapping Writer: %#v", writer.tracer) + log.Debugf("contrib/segmentio/kafka.go.v0: Wrapping Writer: %#v", writer.tracer) return writer } diff --git a/contrib/syndtr/goleveldb/leveldb/leveldb.go b/contrib/syndtr/goleveldb/leveldb/leveldb.go index 8047d6bf72..08e8eed182 100644 --- a/contrib/syndtr/goleveldb/leveldb/leveldb.go +++ b/contrib/syndtr/goleveldb/leveldb/leveldb.go @@ -57,7 +57,7 @@ func OpenFile(path string, o *opt.Options, opts ...Option) (*DB, error) { // WrapDB wraps a leveldb.DB so that queries are traced. func WrapDB(db *leveldb.DB, opts ...Option) *DB { cfg := newConfig(opts...) - log.Debug("contrib/syndtr/goleveldb/leveldb: Wrapping DB: %#v", cfg) + log.Debugf("contrib/syndtr/goleveldb/leveldb: Wrapping DB: %#v", cfg) return &DB{ DB: db, cfg: cfg, diff --git a/contrib/tidwall/buntdb/buntdb.go b/contrib/tidwall/buntdb/buntdb.go index 363a08db62..aae35ad1ca 100644 --- a/contrib/tidwall/buntdb/buntdb.go +++ b/contrib/tidwall/buntdb/buntdb.go @@ -94,7 +94,7 @@ func WrapTx(tx *buntdb.Tx, opts ...Option) *Tx { for _, opt := range opts { opt(cfg) } - log.Debug("contrib/tidwall/buntdb: Wrapping Transaction: %#v", cfg) + log.Debugf("contrib/tidwall/buntdb: Wrapping Transaction: %#v", cfg) return &Tx{ Tx: tx, cfg: cfg, diff --git a/contrib/twitchtv/twirp/twirp.go b/contrib/twitchtv/twirp/twirp.go index 19515575f5..2912e722e2 100644 --- a/contrib/twitchtv/twirp/twirp.go +++ b/contrib/twitchtv/twirp/twirp.go @@ -54,7 +54,7 @@ func WrapClient(c HTTPClient, opts ...Option) HTTPClient { for _, fn := range opts { fn(cfg) } - log.Debug("contrib/twitchtv/twirp: Wrapping Client: %#v", cfg) + log.Debugf("contrib/twitchtv/twirp: Wrapping Client: %#v", cfg) return &wrappedClient{c: c, cfg: cfg} } @@ -98,7 +98,7 @@ func (wc *wrappedClient) Do(req *http.Request) (*http.Response, error) { err := tracer.Inject(span.Context(), tracer.HTTPHeadersCarrier(req.Header)) if err != nil { - log.Warn("contrib/twitchtv/twirp.wrappedClient: failed to inject http headers: %v\n", err) + log.Warnf("contrib/twitchtv/twirp.wrappedClient: failed to inject http headers: %v\n", err) } req = req.WithContext(ctx) @@ -123,7 +123,7 @@ func WrapServer(h http.Handler, opts ...Option) http.Handler { for _, fn := range opts { fn(cfg) } - log.Debug("contrib/twitchtv/twirp: Wrapping Server: %#v", cfg) + log.Debugf("contrib/twitchtv/twirp: Wrapping Server: %#v", cfg) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { spanOpts := []tracer.StartSpanOption{ tracer.SpanType(ext.SpanTypeWeb), @@ -157,7 +157,7 @@ func NewServerHooks(opts ...Option) *twirp.ServerHooks { for _, fn := range opts { fn(cfg) } - log.Debug("contrib/twitchtv/twirp: Creating Server Hooks: %#v", cfg) + log.Debugf("contrib/twitchtv/twirp: Creating Server Hooks: %#v", cfg) return &twirp.ServerHooks{ RequestReceived: requestReceivedHook(cfg), RequestRouted: requestRoutedHook(), diff --git a/contrib/urfave/negroni/negroni.go b/contrib/urfave/negroni/negroni.go index 651188df1a..e3e51fd3a3 100644 --- a/contrib/urfave/negroni/negroni.go +++ b/contrib/urfave/negroni/negroni.go @@ -71,7 +71,7 @@ func Middleware(opts ...Option) *DatadogMiddleware { } cfg.spanOpts = append(cfg.spanOpts, tracer.Tag(ext.Component, componentName)) cfg.spanOpts = append(cfg.spanOpts, tracer.Tag(ext.SpanKind, ext.SpanKindServer)) - log.Debug("contrib/urgave/negroni: Configuring Middleware: %#v", cfg) + log.Debugf("contrib/urgave/negroni: Configuring Middleware: %#v", cfg) m := DatadogMiddleware{ cfg: cfg, diff --git a/contrib/valyala/fasthttp.v1/fasthttp.go b/contrib/valyala/fasthttp.v1/fasthttp.go index 7d803b8652..dd2e2a5af7 100644 --- a/contrib/valyala/fasthttp.v1/fasthttp.go +++ b/contrib/valyala/fasthttp.v1/fasthttp.go @@ -32,7 +32,7 @@ func WrapHandler(h fasthttp.RequestHandler, opts ...Option) fasthttp.RequestHand for _, fn := range opts { fn(cfg) } - log.Debug("contrib/valyala/fasthttp.v1: Configuring Middleware: cfg: %#v", cfg) + log.Debugf("contrib/valyala/fasthttp.v1: Configuring Middleware: cfg: %#v", cfg) return func(fctx *fasthttp.RequestCtx) { if cfg.ignoreRequest(fctx) { h(fctx) diff --git a/contrib/zenazn/goji.v1/web/goji.go b/contrib/zenazn/goji.v1/web/goji.go index 7efe46d8aa..e3c5aa9429 100644 --- a/contrib/zenazn/goji.v1/web/goji.go +++ b/contrib/zenazn/goji.v1/web/goji.go @@ -47,7 +47,7 @@ func Middleware(opts ...Option) func(*web.C, http.Handler) http.Handler { cfg.spanOpts = append(cfg.spanOpts, tracer.Tag(ext.Component, componentName)) cfg.spanOpts = append(cfg.spanOpts, tracer.Tag(ext.SpanKind, ext.SpanKindServer)) - log.Debug("contrib/zenazn/goji.v1/web: Configuring Middleware: %#v", cfg) + log.Debugf("contrib/zenazn/goji.v1/web: Configuring Middleware: %#v", cfg) return func(c *web.C, h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { resource := r.Method diff --git a/ddtrace/opentelemetry/span.go b/ddtrace/opentelemetry/span.go index 91abe11a78..ee1da84930 100644 --- a/ddtrace/opentelemetry/span.go +++ b/ddtrace/opentelemetry/span.go @@ -139,7 +139,7 @@ func (s *span) extractTraceData(c *oteltrace.SpanContextConfig) { } state, err := oteltrace.ParseTraceState(headers["tracestate"]) if err != nil { - log.Debug("Couldn't parse tracestate: %v", err) + log.Debugf("Couldn't parse tracestate: %v", err) return } c.TraceState = state @@ -150,7 +150,7 @@ func (s *span) extractTraceData(c *oteltrace.SpanContextConfig) { // where flags represents the propagated flags in the format of 2 hex-encoded digits at the end of the traceparent. otelFlagLen := 2 if f, err := strconv.ParseUint(parent[len(parent)-otelFlagLen:], 16, 8); err != nil { - log.Debug("Couldn't parse traceparent: %v", err) + log.Debugf("Couldn't parse traceparent: %v", err) } else { c.TraceFlags = oteltrace.TraceFlags(f) } diff --git a/ddtrace/tracer/abandonedspans.go b/ddtrace/tracer/abandonedspans.go index e94b0ec39e..48cad86a68 100644 --- a/ddtrace/tracer/abandonedspans.go +++ b/ddtrace/tracer/abandonedspans.go @@ -268,12 +268,12 @@ func (d *abandonedSpansDebugger) log(interval *time.Duration) { return } - log.Warn("%d abandoned spans:", spanCount) + log.Warnf("%d abandoned spans:", spanCount) if truncated { log.Warn("Too many abandoned spans. Truncating message.") sb.WriteString("...") } - log.Warn("%s", sb.String()) + log.Warn(sb.String()) } // formatAbandonedSpans takes a bucket and returns a human-readable string representing diff --git a/ddtrace/tracer/civisibility_payload.go b/ddtrace/tracer/civisibility_payload.go index f630f299b5..4c6a76ac95 100644 --- a/ddtrace/tracer/civisibility_payload.go +++ b/ddtrace/tracer/civisibility_payload.go @@ -73,7 +73,7 @@ func newCiVisibilityPayload() *ciVisibilityPayload { // An error if reading from the buffer or encoding the payload fails. func (p *ciVisibilityPayload) getBuffer(config *config) (*bytes.Buffer, error) { startTime := time.Now() - log.Debug("ciVisibilityPayload: .getBuffer (count: %v)", p.itemCount()) + log.Debugf("ciVisibilityPayload: .getBuffer (count: %v)", p.itemCount()) // Create a buffer to read the current payload payloadBuf := new(bytes.Buffer) diff --git a/ddtrace/tracer/civisibility_transport.go b/ddtrace/tracer/civisibility_transport.go index 9910ea8fd3..85257960f2 100644 --- a/ddtrace/tracer/civisibility_transport.go +++ b/ddtrace/tracer/civisibility_transport.go @@ -107,7 +107,7 @@ func newCiVisibilityTransport(config *config) *ciVisibilityTransport { testCycleURL = fmt.Sprintf("%s/%s/%s", config.agentURL.String(), EvpProxyPath, TestCyclePath) } - log.Debug("ciVisibilityTransport: creating transport instance [agentless: %v, testcycleurl: %v]", agentlessEnabled, testCycleURL) + log.Debugf("ciVisibilityTransport: creating transport instance [agentless: %v, testcycleurl: %v]", agentlessEnabled, testCycleURL) return &ciVisibilityTransport{ config: config, @@ -160,7 +160,7 @@ func (t *ciVisibilityTransport) send(p *payload) (body io.ReadCloser, err error) req.Header.Set("Content-Encoding", "gzip") } - log.Debug("ciVisibilityTransport: sending transport request: %v bytes", buffer.Len()) + log.Debugf("ciVisibilityTransport: sending transport request: %v bytes", buffer.Len()) startTime := time.Now() response, err := t.config.httpClient.Do(req) telemetry.EndpointPayloadRequestsMs(telemetry.TestCycleEndpointType, float64(time.Since(startTime).Milliseconds())) diff --git a/ddtrace/tracer/civisibility_writer.go b/ddtrace/tracer/civisibility_writer.go index 1a5417b0b2..65d671e97b 100644 --- a/ddtrace/tracer/civisibility_writer.go +++ b/ddtrace/tracer/civisibility_writer.go @@ -65,7 +65,7 @@ func (w *ciVisibilityTraceWriter) add(trace []*span) { for _, s := range trace { cvEvent := getCiVisibilityEvent(s) if err := w.payload.push(cvEvent); err != nil { - log.Error("ciVisibilityTraceWriter: Error encoding msgpack: %v", err) + log.Errorf("ciVisibilityTraceWriter: Error encoding msgpack: %v", err) } if w.payload.size() > agentlessPayloadSizeLimit { w.flush() @@ -114,17 +114,17 @@ func (w *ciVisibilityTraceWriter) flush() { for attempt := 0; attempt <= w.config.sendRetries; attempt++ { size, count = p.size(), p.itemCount() - log.Debug("ciVisibilityTraceWriter: sending payload: size: %d events: %d\n", size, count) + log.Debugf("ciVisibilityTraceWriter: sending payload: size: %d events: %d\n", size, count) _, err = w.config.transport.send(p.payload) if err == nil { - log.Debug("ciVisibilityTraceWriter: sent events after %d attempts", attempt+1) + log.Debugf("ciVisibilityTraceWriter: sent events after %d attempts", attempt+1) return } - log.Error("ciVisibilityTraceWriter: failure sending events (attempt %d), will retry: %v", attempt+1, err) + log.Errorf("ciVisibilityTraceWriter: failure sending events (attempt %d), will retry: %v", attempt+1, err) p.reset() time.Sleep(time.Millisecond) } - log.Error("ciVisibilityTraceWriter: lost %d events: %v", count, err) + log.Errorf("ciVisibilityTraceWriter: lost %d events: %v", count, err) telemetry.EndpointPayloadDropped(telemetry.TestCycleEndpointType) }(oldp) } diff --git a/ddtrace/tracer/log.go b/ddtrace/tracer/log.go index 5b6e056f28..40aaf670d1 100644 --- a/ddtrace/tracer/log.go +++ b/ddtrace/tracer/log.go @@ -157,13 +157,13 @@ func logStartup(t *tracer) { if !t.config.logToStdout { if err := checkEndpoint(t.config.httpClient, t.config.transport.endpoint()); err != nil { info.AgentError = fmt.Sprintf("%s", err) - log.Warn("DIAGNOSTICS Unable to reach agent intake: %s", err) + log.Warnf("DIAGNOSTICS Unable to reach agent intake: %s", err) } } bs, err := json.Marshal(info) if err != nil { - log.Warn("DIAGNOSTICS Failed to serialize json for startup log (%v) %#v\n", err, info) + log.Warnf("DIAGNOSTICS Failed to serialize json for startup log (%v) %#v\n", err, info) return } - log.Info("DATADOG TRACER CONFIGURATION %s\n", string(bs)) + log.Infof("DATADOG TRACER CONFIGURATION %s\n", string(bs)) } diff --git a/ddtrace/tracer/option.go b/ddtrace/tracer/option.go index dbffa546df..0ddf358992 100644 --- a/ddtrace/tracer/option.go +++ b/ddtrace/tracer/option.go @@ -331,10 +331,10 @@ func newConfig(opts ...StartOption) *config { var err error sampleRate, err = strconv.ParseFloat(r, 64) if err != nil { - log.Warn("ignoring DD_TRACE_SAMPLE_RATE, error: %v", err) + log.Warnf("ignoring DD_TRACE_SAMPLE_RATE, error: %v", err) sampleRate = math.NaN() } else if sampleRate < 0.0 || sampleRate > 1.0 { - log.Warn("ignoring DD_TRACE_SAMPLE_RATE: out of range %f", sampleRate) + log.Warnf("ignoring DD_TRACE_SAMPLE_RATE: out of range %f", sampleRate) sampleRate = math.NaN() } } @@ -351,7 +351,7 @@ func newConfig(opts ...StartOption) *config { var err error c.hostname, err = os.Hostname() if err != nil { - log.Warn("unable to look up hostname: %v", err) + log.Warnf("unable to look up hostname: %v", err) } } if v := os.Getenv("DD_TRACE_SOURCE_HOSTNAME"); v != "" { @@ -410,7 +410,7 @@ func newConfig(opts ...StartOption) *config { if semver.IsValid(compatMode) { c.enableHostnameDetection = semver.Compare(semver.MajorMinor(compatMode), "v1.66") <= 0 } else { - log.Warn("ignoring DD_TRACE_CLIENT_HOSTNAME_COMPAT, invalid version %q", compatMode) + log.Warnf("ignoring DD_TRACE_CLIENT_HOSTNAME_COMPAT, invalid version %q", compatMode) } } c.debugAbandonedSpans = internal.BoolEnv("DD_TRACE_DEBUG_ABANDONED_SPANS", false) @@ -422,10 +422,10 @@ func newConfig(opts ...StartOption) *config { c.partialFlushEnabled = internal.BoolEnv("DD_TRACE_PARTIAL_FLUSH_ENABLED", false) c.partialFlushMinSpans = internal.IntEnv("DD_TRACE_PARTIAL_FLUSH_MIN_SPANS", partialFlushMinSpansDefault) if c.partialFlushMinSpans <= 0 { - log.Warn("DD_TRACE_PARTIAL_FLUSH_MIN_SPANS=%d is not a valid value, setting to default %d", c.partialFlushMinSpans, partialFlushMinSpansDefault) + log.Warnf("DD_TRACE_PARTIAL_FLUSH_MIN_SPANS=%d is not a valid value, setting to default %d", c.partialFlushMinSpans, partialFlushMinSpansDefault) c.partialFlushMinSpans = partialFlushMinSpansDefault } else if c.partialFlushMinSpans >= traceMaxSize { - log.Warn("DD_TRACE_PARTIAL_FLUSH_MIN_SPANS=%d is above the max number of spans that can be kept in memory for a single trace (%d spans), so partial flushing will never trigger, setting to default %d", c.partialFlushMinSpans, traceMaxSize, partialFlushMinSpansDefault) + log.Warnf("DD_TRACE_PARTIAL_FLUSH_MIN_SPANS=%d is above the max number of spans that can be kept in memory for a single trace (%d spans), so partial flushing will never trigger, setting to default %d", c.partialFlushMinSpans, traceMaxSize, partialFlushMinSpansDefault) c.partialFlushMinSpans = partialFlushMinSpansDefault } // TODO(partialFlush): consider logging a warning if DD_TRACE_PARTIAL_FLUSH_MIN_SPANS @@ -441,7 +441,7 @@ func newConfig(opts ...StartOption) *config { } else { v := namingschema.SetDefaultVersion() c.spanAttributeSchemaVersion = int(v) - log.Warn("DD_TRACE_SPAN_ATTRIBUTE_SCHEMA=%s is not a valid value, setting to default of v%d", schemaVersionStr, v) + log.Warnf("DD_TRACE_SPAN_ATTRIBUTE_SCHEMA=%s is not a valid value, setting to default of v%d", schemaVersionStr, v) } // Allow DD_TRACE_SPAN_ATTRIBUTE_SCHEMA=v0 users to disable default integration (contrib AKA v0) service names. // These default service names are always disabled for v1 onwards. @@ -512,11 +512,11 @@ func newConfig(opts ...StartOption) *config { envKey := "DD_TRACE_X_DATADOG_TAGS_MAX_LENGTH" max := internal.IntEnv(envKey, defaultMaxTagsHeaderLen) if max < 0 { - log.Warn("Invalid value %d for %s. Setting to 0.", max, envKey) + log.Warnf("Invalid value %d for %s. Setting to 0.", max, envKey) max = 0 } if max > maxPropagatedTagsLength { - log.Warn("Invalid value %d for %s. Maximum allowed is %d. Setting to %d.", max, envKey, maxPropagatedTagsLength, maxPropagatedTagsLength) + log.Warnf("Invalid value %d for %s. Maximum allowed is %d. Setting to %d.", max, envKey, maxPropagatedTagsLength, maxPropagatedTagsLength) max = maxPropagatedTagsLength } c.propagator = NewPropagator(&PropagatorConfig{ @@ -694,7 +694,7 @@ func loadAgentFeatures(agentDisabled bool, agentURL *url.URL, httpClient *http.C } resp, err := httpClient.Get(fmt.Sprintf("%s/info", agentURL)) if err != nil { - log.Error("Loading features: %v", err) + log.Errorf("Loading features: %v", err) return } if resp.StatusCode == http.StatusNotFound { @@ -714,7 +714,7 @@ func loadAgentFeatures(agentDisabled bool, agentURL *url.URL, httpClient *http.C var info infoResponse if err := json.NewDecoder(resp.Body).Decode(&info); err != nil { - log.Error("Decoding features: %v", err) + log.Errorf("Decoding features: %v", err) return } features.DropP0s = info.ClientDropP0s @@ -833,7 +833,7 @@ func WithFeatureFlags(feats ...string) StartOption { for _, f := range feats { c.featureFlags[strings.TrimSpace(f)] = struct{}{} } - log.Info("FEATURES enabled: %v", feats) + log.Infof("FEATURES enabled: %v", feats) } } @@ -1366,7 +1366,7 @@ func setHeaderTags(headerAsTags []string) bool { for _, h := range headerAsTags { header, tag := normalizer.HeaderTag(h) if len(header) == 0 || len(tag) == 0 { - log.Debug("Header-tag input is in unsupported format; dropping input value %v", h) + log.Debugf("Header-tag input is in unsupported format; dropping input value %v", h) continue } globalconfig.SetHeaderTag(header, tag) diff --git a/ddtrace/tracer/otel_dd_mappings.go b/ddtrace/tracer/otel_dd_mappings.go index ec8ebb10ee..788f134651 100644 --- a/ddtrace/tracer/otel_dd_mappings.go +++ b/ddtrace/tracer/otel_dd_mappings.go @@ -92,13 +92,13 @@ func getDDorOtelConfig(configName string) string { ddPrefix := "config_datadog:" otelPrefix := "config_opentelemetry:" if val != "" { - log.Warn("Both %v and %v are set, using %v=%v", config.ot, config.dd, config.dd, val) + log.Warnf("Both %v and %v are set, using %v=%v", config.ot, config.dd, config.dd, val) telemetryTags := []string{ddPrefix + strings.ToLower(config.dd), otelPrefix + strings.ToLower(config.ot)} telemetry.GlobalClient.Count(telemetry.NamespaceTracers, "otel.env.hiding", 1.0, telemetryTags, true) } else { v, err := config.remapper(otVal) if err != nil { - log.Warn("%s", err.Error()) + log.Warn(err.Error()) telemetryTags := []string{ddPrefix + strings.ToLower(config.dd), otelPrefix + strings.ToLower(config.ot)} telemetry.GlobalClient.Count(telemetry.NamespaceTracers, "otel.env.invalid", 1.0, telemetryTags, true) } @@ -122,7 +122,7 @@ func mapDDTags(ot string) (string, error) { }) if len(ddTags) > 10 { - log.Warn("The following resource attributes have been dropped: %v. Only the first 10 resource attributes will be applied: %v", ddTags[10:], ddTags[:10]) + log.Warnf("The following resource attributes have been dropped: %v. Only the first 10 resource attributes will be applied: %v", ddTags[10:], ddTags[:10]) ddTags = ddTags[:10] } @@ -171,7 +171,7 @@ func otelTraceIDRatio() string { func mapSampleRate(ot string) (string, error) { ot = strings.TrimSpace(strings.ToLower(ot)) if v, ok := unsupportedSamplerMapping[ot]; ok { - log.Warn("The following configuration is not supported: OTEL_TRACES_SAMPLER=%v. %v will be used", ot, v) + log.Warnf("The following configuration is not supported: OTEL_TRACES_SAMPLER=%v. %v will be used", ot, v) ot = v } @@ -195,7 +195,7 @@ func mapPropagationStyle(ot string) (string, error) { if _, ok := propagationMapping[otStyle]; ok { supportedStyles = append(supportedStyles, propagationMapping[otStyle]) } else { - log.Warn("Invalid configuration: %v is not supported. This propagation style will be ignored.", otStyle) + log.Warnf("Invalid configuration: %v is not supported. This propagation style will be ignored.", otStyle) } } return strings.Join(supportedStyles, ","), nil diff --git a/ddtrace/tracer/remote_config.go b/ddtrace/tracer/remote_config.go index eaa8641730..04eacd13f8 100644 --- a/ddtrace/tracer/remote_config.go +++ b/ddtrace/tracer/remote_config.go @@ -161,7 +161,7 @@ func (t *tracer) onRemoteConfigUpdate(u remoteconfig.ProductUpdate) map[string]s // The remote-config client is signaling that the configuration has been deleted for this product. // We re-apply the startup configuration values. for path := range u { - log.Debug("Nil payload from RC. Path: %s.", path) + log.Debugf("Nil payload from RC. Path: %s.", path) statuses[path] = state.ApplyStatus{State: state.ApplyStateAcknowledged} } log.Debug("Resetting configurations") @@ -185,7 +185,7 @@ func (t *tracer) onRemoteConfigUpdate(u remoteconfig.ProductUpdate) map[string]s log.Debug("APM Tracing is disabled. Restart the service to enable it.") } if len(telemConfigs) > 0 { - log.Debug("Reporting %d configuration changes to telemetry", len(telemConfigs)) + log.Debugf("Reporting %d configuration changes to telemetry", len(telemConfigs)) telemetry.GlobalClient.ConfigChange(telemConfigs) } return statuses @@ -194,15 +194,15 @@ func (t *tracer) onRemoteConfigUpdate(u remoteconfig.ProductUpdate) map[string]s if raw == nil { continue } - log.Debug("Processing config from RC. Path: %s. Raw: %s", path, raw) + log.Debugf("Processing config from RC. Path: %s. Raw: %s", path, raw) var c configData if err := json.Unmarshal(raw, &c); err != nil { - log.Debug("Error while unmarshalling payload for %s: %v. Configuration won't be applied.", path, err) + log.Debugf("Error while unmarshalling payload for %s: %v. Configuration won't be applied.", path, err) statuses[path] = state.ApplyStatus{State: state.ApplyStateError, Error: err.Error()} continue } if c.ServiceTarget.Service != t.config.serviceName { - log.Debug( + log.Debugf( "Skipping config for service %s. Current service is %s", c.ServiceTarget.Service, t.config.serviceName, @@ -211,7 +211,7 @@ func (t *tracer) onRemoteConfigUpdate(u remoteconfig.ProductUpdate) map[string]s continue } if c.ServiceTarget.Env != t.config.env { - log.Debug("Skipping config for env %s. Current env is %s", c.ServiceTarget.Env, t.config.env) + log.Debugf("Skipping config for env %s. Current env is %s", c.ServiceTarget.Env, t.config.env) statuses[path] = state.ApplyStatus{State: state.ApplyStateError, Error: "env mismatch"} continue } @@ -243,7 +243,7 @@ func (t *tracer) onRemoteConfigUpdate(u remoteconfig.ProductUpdate) map[string]s } } if len(telemConfigs) > 0 { - log.Debug("Reporting %d configuration changes to telemetry", len(telemConfigs)) + log.Debugf("Reporting %d configuration changes to telemetry", len(telemConfigs)) telemetry.GlobalClient.ConfigChange(telemConfigs) } return statuses @@ -270,7 +270,7 @@ func (t *tracer) dynamicInstrumentationRCUpdate(u remoteconfig.ProductUpdate) ma diRCState.Lock() for k, v := range u { - log.Debug("Received dynamic instrumentation RC configuration for %s\n", k) + log.Debugf("Received dynamic instrumentation RC configuration for %s\n", k) applyStatus[k] = state.ApplyStatus{State: state.ApplyStateUnknown} diRCState.state[k] = dynamicInstrumentationRCProbeConfig{ runtimeID: globalconfig.RuntimeID(), diff --git a/ddtrace/tracer/rules_sampler.go b/ddtrace/tracer/rules_sampler.go index 037e393642..639d70029a 100644 --- a/ddtrace/tracer/rules_sampler.go +++ b/ddtrace/tracer/rules_sampler.go @@ -409,7 +409,7 @@ func EqualsFalseNegative(a, b []SamplingRule) bool { // Returns whether the value was changed or not. func (rs *traceRulesSampler) setGlobalSampleRate(rate float64) bool { if rate < 0.0 || rate > 1.0 { - log.Warn("Ignoring trace sample rate %f: value out of range [0,1]", rate) + log.Warnf("Ignoring trace sample rate %f: value out of range [0,1]", rate) return false } rs.m.Lock() @@ -539,9 +539,9 @@ func newRateLimiter() *rateLimiter { if v != "" { l, err := strconv.ParseFloat(v, 64) if err != nil { - log.Warn("DD_TRACE_RATE_LIMIT invalid, using default value %f: %v", limit, err) + log.Warnf("DD_TRACE_RATE_LIMIT invalid, using default value %f: %v", limit, err) } else if l < 0.0 { - log.Warn("DD_TRACE_RATE_LIMIT negative, using default value %f", limit) + log.Warnf("DD_TRACE_RATE_LIMIT negative, using default value %f", limit) } else { // override the default limit origin = telemetry.OriginEnvVar @@ -708,7 +708,7 @@ func samplingRulesFromEnv() (trace, span []SamplingRule, err error) { rulesFile := os.Getenv(env + "_FILE") if len(rules) != 0 { if rulesFile != "" { - log.Warn("DIAGNOSTICS Error(s): %s is available and will take precedence over %s_FILE", env, env) + log.Warnf("DIAGNOSTICS Error(s): %s is available and will take precedence over %s_FILE", env, env) } return rules, errs } @@ -899,7 +899,7 @@ func (sr SamplingRule) MarshalJSON() ([]byte, error) { func (sr SamplingRule) String() string { s, err := sr.MarshalJSON() if err != nil { - log.Error("Error marshalling SamplingRule to json: %v", err) + log.Errorf("Error marshalling SamplingRule to json: %v", err) } return string(s) } diff --git a/ddtrace/tracer/slog.go b/ddtrace/tracer/slog.go index 02523bc23b..06a477d02d 100644 --- a/ddtrace/tracer/slog.go +++ b/ddtrace/tracer/slog.go @@ -41,13 +41,13 @@ func (h slogHandler) Handle(ctx context.Context, r slog.Record) error { msg := strings.Join(parts, " ") switch r.Level { case slog.LevelDebug: - log.Debug("%s", msg) + log.Debug(msg) case slog.LevelInfo: - log.Info("%s", msg) + log.Info(msg) case slog.LevelWarn: - log.Warn("%s", msg) + log.Warn(msg) case slog.LevelError: - log.Error("%s", msg) + log.Error(msg) } return nil } diff --git a/ddtrace/tracer/span.go b/ddtrace/tracer/span.go index ebfa681fb3..f15da060ef 100644 --- a/ddtrace/tracer/span.go +++ b/ddtrace/tracer/span.go @@ -584,7 +584,7 @@ func (s *span) finish(finishTime int64) { } if log.DebugEnabled() { // avoid allocating the ...interface{} argument if debug logging is disabled - log.Debug("Finished Span: %v, Operation: %s, Resource: %s, Tags: %v, %v", + log.Debugf("Finished Span: %v, Operation: %s, Resource: %s, Tags: %v, %v", s, s.Name, s.Resource, s.Meta, s.Metrics) } s.context.finish() @@ -610,7 +610,7 @@ func obfuscatedResource(o *obfuscate.Obfuscator, typ, resource string) string { case "sql", "cassandra": oq, err := o.ObfuscateSQLString(resource) if err != nil { - log.Error("Error obfuscating stats group resource %q: %v", resource, err) + log.Errorf("Error obfuscating stats group resource %q: %v", resource, err) return textNonParsable } return oq.Query diff --git a/ddtrace/tracer/spancontext.go b/ddtrace/tracer/spancontext.go index 30a791ee8e..57ffd0ec3a 100644 --- a/ddtrace/tracer/spancontext.go +++ b/ddtrace/tracer/spancontext.go @@ -409,7 +409,7 @@ func (t *trace) push(sp *span) { // capacity is reached, we will not be able to complete this trace. t.full = true t.spans = nil // GC - log.Error("trace buffer full (%d), dropping trace", traceMaxSize) + log.Errorf("trace buffer full (%d), dropping trace", traceMaxSize) if haveTracer { atomic.AddUint32(&tr.tracesDropped, 1) } @@ -503,7 +503,7 @@ func (t *trace) finishedOne(s *span) { if !doPartialFlush { return // The trace hasn't completed and partial flushing will not occur } - log.Debug("Partial flush triggered with %d finished spans", t.finished) + log.Debugf("Partial flush triggered with %d finished spans", t.finished) telemetry.GlobalClient.Count(telemetry.NamespaceTracers, "trace_partial_flush.count", 1, []string{"reason:large_trace"}, true) finishedSpans := make([]*span, 0, t.finished) leftoverSpans := make([]*span, 0, len(t.spans)-t.finished) @@ -549,7 +549,7 @@ func setPeerService(s *span, cfg *config) { } source := setPeerServiceFromSource(s) if source == "" { - log.Debug("No source tag value could be found for span %q, peer.service not set", s.Name) + log.Debugf("No source tag value could be found for span %q, peer.service not set", s.Name) return } s.setMeta(keyPeerServiceSource, source) diff --git a/ddtrace/tracer/sqlcomment.go b/ddtrace/tracer/sqlcomment.go index 99232e269a..101a2e888c 100644 --- a/ddtrace/tracer/sqlcomment.go +++ b/ddtrace/tracer/sqlcomment.go @@ -203,7 +203,7 @@ func commentQuery(query string, tags map[string]string) string { if query == "" { return b.String() } - log.Debug("Injected sql comment: %s", b.String()) + log.Debugf("Injected sql comment: %s", b.String()) b.WriteRune(' ') b.WriteString(query) return b.String() diff --git a/ddtrace/tracer/stats.go b/ddtrace/tracer/stats.go index da505623aa..3b608e549f 100644 --- a/ddtrace/tracer/stats.go +++ b/ddtrace/tracer/stats.go @@ -210,7 +210,7 @@ func (c *concentrator) flushAndSend(timenow time.Time, includeCurrent bool) { flushedBuckets += len(csp.Stats) if err := c.cfg.transport.sendStats(csp); err != nil { c.statsd().Incr("datadog.tracer.stats.flush_errors", nil, 1) - log.Error("Error sending stats payload: %v", err) + log.Errorf("Error sending stats payload: %v", err) } } c.statsd().Incr("datadog.tracer.stats.flush_buckets", nil, float64(flushedBuckets)) diff --git a/ddtrace/tracer/textmap.go b/ddtrace/tracer/textmap.go index 1fee0ba689..050d397f26 100644 --- a/ddtrace/tracer/textmap.go +++ b/ddtrace/tracer/textmap.go @@ -165,13 +165,13 @@ func NewPropagator(cfg *PropagatorConfig, propagators ...Propagator) Propagator injectorsPs := os.Getenv(headerPropagationStyleInject) if injectorsPs == "" { if injectorsPs = os.Getenv(headerPropagationStyleInjectDeprecated); injectorsPs != "" { - log.Warn("%v is deprecated. Please use %v or %v instead.\n", headerPropagationStyleInjectDeprecated, headerPropagationStyleInject, headerPropagationStyle) + log.Warnf("%v is deprecated. Please use %v or %v instead.\n", headerPropagationStyleInjectDeprecated, headerPropagationStyleInject, headerPropagationStyle) } } extractorsPs := os.Getenv(headerPropagationStyleExtract) if extractorsPs == "" { if extractorsPs = os.Getenv(headerPropagationStyleExtractDeprecated); extractorsPs != "" { - log.Warn("%v is deprecated. Please use %v or %v instead.\n", headerPropagationStyleExtractDeprecated, headerPropagationStyleExtract, headerPropagationStyle) + log.Warnf("%v is deprecated. Please use %v or %v instead.\n", headerPropagationStyleExtractDeprecated, headerPropagationStyleExtract, headerPropagationStyle) } } cp.injectors, cp.injectorNames = getPropagators(cfg, injectorsPs) @@ -240,7 +240,7 @@ func getPropagators(cfg *PropagatorConfig, ps string) ([]Propagator, string) { log.Warn("Propagator \"none\" has no effect when combined with other propagators. " + "To disable the propagator, set to `none`") default: - log.Warn("unrecognized propagator: %s\n", v) + log.Warnf("unrecognized propagator: %s\n", v) } } if len(list) == 0 { @@ -307,7 +307,7 @@ func (p *chainedPropagator) Extract(carrier interface{}) (ddtrace.SpanContext, e if ctx == nil { return nil, ErrSpanContextNotFound } - log.Debug("Extracted span context: %#v", ctx) + log.Debugf("Extracted span context: %#v", ctx) return ctx, nil } @@ -395,13 +395,13 @@ func (p *propagator) marshalPropagatingTags(ctx *spanContext) string { return true // don't propagate W3C headers with the DD propagator } if err := isValidPropagatableTag(k, v); err != nil { - log.Warn("Won't propagate tag '%s': %v", k, err.Error()) + log.Warnf("Won't propagate tag '%s': %v", k, err.Error()) properr = "encoding_error" return true } if tagLen := sb.Len() + len(k) + len(v); tagLen > p.cfg.MaxTagsHeaderLen { sb.Reset() - log.Warn("Won't propagate tag: length is (%d) which exceeds the maximum len of (%d).", tagLen, p.cfg.MaxTagsHeaderLen) + log.Warnf("Won't propagate tag: length is (%d) which exceeds the maximum len of (%d).", tagLen, p.cfg.MaxTagsHeaderLen) properr = "inject_max_size" return false } @@ -469,10 +469,10 @@ func (p *propagator) extractTextMap(reader TextMapReader) (ddtrace.SpanContext, if ctx.trace != nil { tid := ctx.trace.propagatingTag(keyTraceID128) if err := validateTID(tid); err != nil { - log.Debug("Invalid hex traceID: %s", err) + log.Debugf("Invalid hex traceID: %s", err) ctx.trace.unsetPropagatingTag(keyTraceID128) } else if err := ctx.traceID.SetUpperFromHex(tid); err != nil { - log.Debug("Attempted to set an invalid hex traceID: %s", err) + log.Debugf("Attempted to set an invalid hex traceID: %s", err) ctx.trace.unsetPropagatingTag(keyTraceID128) } } @@ -521,13 +521,13 @@ func unmarshalPropagatingTags(ctx *spanContext, v string) { ctx.trace = newTrace() } if len(v) > propagationExtractMaxSize { - log.Warn("Did not extract %s, size limit exceeded: %d. Incoming tags will not be propagated further.", traceTagsHeader, propagationExtractMaxSize) + log.Warnf("Did not extract %s, size limit exceeded: %d. Incoming tags will not be propagated further.", traceTagsHeader, propagationExtractMaxSize) ctx.trace.setTag(keyPropagationError, "extract_max_size") return } tags, err := parsePropagatableTraceTags(v) if err != nil { - log.Warn("Did not extract %s: %v. Incoming tags will not be propagated further.", traceTagsHeader, err.Error()) + log.Warnf("Did not extract %s: %v. Incoming tags will not be propagated further.", traceTagsHeader, err.Error()) ctx.trace.setTag(keyPropagationError, "decoding_error") } ctx.trace.replacePropagatingTags(tags) diff --git a/ddtrace/tracer/tracer.go b/ddtrace/tracer/tracer.go index 89277045de..8e586fe31f 100644 --- a/ddtrace/tracer/tracer.go +++ b/ddtrace/tracer/tracer.go @@ -173,7 +173,7 @@ func Start(opts ...StartOption) { cfg.HTTP = t.config.httpClient cfg.ServiceName = t.config.serviceName if err := t.startRemoteConfig(cfg); err != nil { - log.Warn("Remote config startup error: %s", err) + log.Warnf("Remote config startup error: %s", err) } // start instrumentation telemetry unless it is disabled through the @@ -247,7 +247,7 @@ func newUnstartedTracer(opts ...StartOption) *tracer { sampler := newPrioritySampler() statsd, err := newStatsdClient(c) if err != nil { - log.Warn("Runtime and health metrics disabled: %v", err) + log.Warnf("Runtime and health metrics disabled: %v", err) } var writer traceWriter if c.ciVisibilityEnabled { @@ -259,7 +259,7 @@ func newUnstartedTracer(opts ...StartOption) *tracer { } traces, spans, err := samplingRulesFromEnv() if err != nil { - log.Warn("DIAGNOSTICS Error(s) parsing sampling rules: found errors:%s", err) + log.Warnf("DIAGNOSTICS Error(s) parsing sampling rules: found errors:%s", err) } if traces != nil { c.traceRules = traces @@ -286,7 +286,7 @@ func newUnstartedTracer(opts ...StartOption) *tracer { if v := c.logDirectory; v != "" { logFile, err = log.OpenFileAtPath(v) if err != nil { - log.Warn("%v", err) + log.Warnf("%v", err) c.logDirectory = "" } } @@ -484,13 +484,13 @@ func (t *tracer) pushChunk(trace *chunk) { select { case t.out <- trace: default: - log.Debug("payload queue full, trace dropped %d spans", len(trace.spans)) + log.Debugf("payload queue full, trace dropped %d spans", len(trace.spans)) atomic.AddUint32(&t.totalTracesDropped, 1) } select { case <-t.logDroppedTraces.C: if t := atomic.SwapUint32(&t.totalTracesDropped, 0); t > 0 { - log.Error("%d traces dropped through payload queue", t) + log.Errorf("%d traces dropped through payload queue", t) } default: } @@ -636,7 +636,7 @@ func (t *tracer) StartSpan(operationName string, options ...ddtrace.StartSpanOpt } if log.DebugEnabled() { // avoid allocating the ...interface{} argument if debug logging is disabled - log.Debug("Started Span: %v, Operation: %s, Resource: %s, Tags: %v, %v", + log.Debugf("Started Span: %v, Operation: %s, Resource: %s, Tags: %v, %v", span, span.Name, span.Resource, span.Meta, span.Metrics) } if t.config.debugAbandonedSpans { diff --git a/ddtrace/tracer/writer.go b/ddtrace/tracer/writer.go index 04d9c25d98..ca663c07b7 100644 --- a/ddtrace/tracer/writer.go +++ b/ddtrace/tracer/writer.go @@ -65,7 +65,7 @@ func newAgentTraceWriter(c *config, s *prioritySampler, statsdClient globalinter func (h *agentTraceWriter) add(trace []*span) { if err := h.payload.push(trace); err != nil { h.statsd.Incr("datadog.tracer.traces_dropped", []string{"reason:encoding_error"}, 1) - log.Error("Error encoding msgpack: %v", err) + log.Errorf("Error encoding msgpack: %v", err) } if h.payload.size() > payloadSizeLimit { h.statsd.Incr("datadog.tracer.flush_triggered", []string{"reason:size"}, 1) @@ -105,11 +105,11 @@ func (h *agentTraceWriter) flush() { var err error for attempt := 0; attempt <= h.config.sendRetries; attempt++ { size, count = p.size(), p.itemCount() - log.Debug("Sending payload: size: %d traces: %d\n", size, count) + log.Debugf("Sending payload: size: %d traces: %d\n", size, count) var rc io.ReadCloser rc, err = h.config.transport.send(p) if err == nil { - log.Debug("sent traces after %d attempts", attempt+1) + log.Debugf("sent traces after %d attempts", attempt+1) h.statsd.Count("datadog.tracer.flush_bytes", int64(size), nil, 1) h.statsd.Count("datadog.tracer.flush_traces", int64(count), nil, 1) if err := h.prioritySampling.readRatesJSON(rc); err != nil { @@ -117,12 +117,12 @@ func (h *agentTraceWriter) flush() { } return } - log.Error("failure sending traces (attempt %d), will retry: %v", attempt+1, err) + log.Errorf("failure sending traces (attempt %d), will retry: %v", attempt+1, err) p.reset() time.Sleep(time.Millisecond) } h.statsd.Count("datadog.tracer.traces_dropped", int64(count), []string{"reason:send_failed"}, 1) - log.Error("lost %d traces: %v", count, err) + log.Errorf("lost %d traces: %v", count, err) }(oldp) } @@ -230,7 +230,7 @@ func (h *logTraceWriter) encodeSpan(s *span) { h.buf.WriteString(":") jsonValue, err := json.Marshal(v) if err != nil { - log.Error("Error marshaling value %q: %v", v, err) + log.Errorf("Error marshaling value %q: %v", v, err) continue } h.marshalString(string(jsonValue)) @@ -265,7 +265,7 @@ func (h *logTraceWriter) encodeSpan(s *span) { func (h *logTraceWriter) marshalString(str string) { m, err := json.Marshal(str) if err != nil { - log.Error("Error marshaling value %q: %v", str, err) + log.Errorf("Error marshaling value %q: %v", str, err) } else { h.buf.Write(m) } @@ -328,7 +328,7 @@ func (h *logTraceWriter) add(trace []*span) { for len(trace) > 0 { n, err := h.writeTrace(trace) if err != nil { - log.Error("Lost a trace: %s", err.cause) + log.Errorf("Lost a trace: %s", err.cause) h.statsd.Count("datadog.tracer.traces_dropped", 1, []string{"reason:" + err.dropReason}, 1) return } diff --git a/internal/agent.go b/internal/agent.go index f4bcdce8b0..49af6bd967 100644 --- a/internal/agent.go +++ b/internal/agent.go @@ -34,13 +34,13 @@ func AgentURLFromEnv() *url.URL { if agentURL := os.Getenv("DD_TRACE_AGENT_URL"); agentURL != "" { u, err := url.Parse(agentURL) if err != nil { - log.Warn("Failed to parse DD_TRACE_AGENT_URL: %v", err) + log.Warnf("Failed to parse DD_TRACE_AGENT_URL: %v", err) } else { switch u.Scheme { case "unix", "http", "https": return u default: - log.Warn("Unsupported protocol %q in Agent URL %q. Must be one of: http, https, unix.", u.Scheme, agentURL) + log.Warnf("Unsupported protocol %q in Agent URL %q. Must be one of: http, https, unix.", u.Scheme, agentURL) } } } diff --git a/internal/appsec/appsec.go b/internal/appsec/appsec.go index c04f8b3a00..321d704095 100644 --- a/internal/appsec/appsec.go +++ b/internal/appsec/appsec.go @@ -73,11 +73,11 @@ func Start(opts ...config.StartOption) { // We need to avoid logging an error to APM tracing users who don't necessarily intend to enable appsec if mode == config.ForcedOn { // DD_APPSEC_ENABLED is explicitly set so we log an error - log.Error("appsec: threats detection cannot be enabled for the following reasons: %v\nappsec: no security activities will be collected. Please contact support at https://docs.datadoghq.com/help/ for help.", err) + log.Errorf("appsec: threats detection cannot be enabled for the following reasons: %v\nappsec: no security activities will be collected. Please contact support at https://docs.datadoghq.com/help/ for help.", err) } else { // DD_APPSEC_ENABLED is not set so we cannot know what the intent is here, we must log a // debug message instead to avoid showing an error to APM-tracing-only users. - log.Debug("appsec: remote activation of threats detection cannot be enabled for the following reasons: %v", err) + log.Debugf("appsec: remote activation of threats detection cannot be enabled for the following reasons: %v", err) } return } @@ -93,12 +93,12 @@ func Start(opts ...config.StartOption) { // Start the remote configuration client log.Debug("appsec: starting the remote configuration client") if err := appsec.startRC(); err != nil { - log.Error("appsec: Remote config: disabled due to an instanciation error: %v", err) + log.Errorf("appsec: Remote config: disabled due to an instanciation error: %v", err) } if mode == config.RCStandby { // AppSec is not enforced by the env var and can be enabled through remote config - log.Debug("appsec: %s is not set, appsec won't start until activated through remote configuration", config.EnvEnabled) + log.Debugf("appsec: %s is not set, appsec won't start until activated through remote configuration", config.EnvEnabled) if err := appsec.enableRemoteActivation(); err != nil { // ASM is not enabled and can't be enabled through remote configuration. Nothing more can be done. logUnexpectedStartError(err) @@ -116,7 +116,7 @@ func Start(opts ...config.StartOption) { // Implement the AppSec log message C1 func logUnexpectedStartError(err error) { - log.Error("appsec: could not start because of an unexpected error: %v\nNo security activities will be collected. Please contact support at https://docs.datadoghq.com/help/ for help.", err) + log.Errorf("appsec: could not start because of an unexpected error: %v\nNo security activities will be collected. Please contact support at https://docs.datadoghq.com/help/ for help.", err) } // Stop AppSec. @@ -163,7 +163,7 @@ func (a *appsec) start(telemetry *appsecTelemetry) error { return fmt.Errorf("error while loading libddwaf: %w", err) } // 2. If there is an error and the loading is ok: log as an informative error where appsec can be used - log.Error("appsec: non-critical error while loading libddwaf: %v", err) + log.Errorf("appsec: non-critical error while loading libddwaf: %v", err) } // Register dyngo listeners @@ -217,9 +217,9 @@ func (a *appsec) stop() { func init() { appsecLog.SetBackend(appsecLog.Backend{ - Debug: log.Debug, - Info: log.Info, - Warn: log.Warn, + Debug: log.Debugf, + Info: log.Infof, + Warn: log.Warnf, Errorf: func(s string, a ...any) error { err := fmt.Errorf(s, a...) log.Error(err.Error()) diff --git a/internal/appsec/config/config.go b/internal/appsec/config/config.go index 7d334017f2..9b7fed908d 100644 --- a/internal/appsec/config/config.go +++ b/internal/appsec/config/config.go @@ -33,7 +33,7 @@ func registerAppConfigTelemetry() { func registerSCAAppConfigTelemetry(client telemetry.Client) { val, defined, err := parseBoolEnvVar(EnvSCAEnabled) if err != nil { - log.Error("appsec: %v", err) + log.Errorf("appsec: %v", err) return } if defined { diff --git a/internal/appsec/config/rules_manager.go b/internal/appsec/config/rules_manager.go index e4e003eda1..8444ec3505 100644 --- a/internal/appsec/config/rules_manager.go +++ b/internal/appsec/config/rules_manager.go @@ -50,7 +50,7 @@ type ( func DefaultRulesFragment() RulesFragment { var f RulesFragment if err := json.Unmarshal([]byte(rules.StaticRecommendedRules), &f); err != nil { - log.Debug("appsec: error unmarshalling default rules: %v", err) + log.Debugf("appsec: error unmarshalling default rules: %v", err) } return f } diff --git a/internal/appsec/emitter/httpsec/roundtripper.go b/internal/appsec/emitter/httpsec/roundtripper.go index 8a7f1f2448..7c58a7221a 100644 --- a/internal/appsec/emitter/httpsec/roundtripper.go +++ b/internal/appsec/emitter/httpsec/roundtripper.go @@ -63,7 +63,7 @@ func ProtectRoundTrip(ctx context.Context, url string) error { dyngo.FinishOperation(op, RoundTripOperationRes{}) if err != nil { - log.Debug("appsec: outgoing http request blocked by the WAF on URL: %s", url) + log.Debugf("appsec: outgoing http request blocked by the WAF on URL: %s", url) return err } diff --git a/internal/appsec/emitter/trace/service_entry_span.go b/internal/appsec/emitter/trace/service_entry_span.go index 98e14b092f..6e2c248293 100644 --- a/internal/appsec/emitter/trace/service_entry_span.go +++ b/internal/appsec/emitter/trace/service_entry_span.go @@ -151,7 +151,7 @@ func (op *ServiceEntrySpanOperation) Finish(span TagSetter) { for k, v := range op.jsonTags { strValue, err := json.Marshal(v) if err != nil { - log.Debug("appsec: failed to marshal tag %s: %v", k, err) + log.Debugf("appsec: failed to marshal tag %s: %v", k, err) } span.SetTag(k, string(strValue)) } diff --git a/internal/appsec/emitter/waf/actions/actions.go b/internal/appsec/emitter/waf/actions/actions.go index 4eabcfaff6..5a6cd5a724 100644 --- a/internal/appsec/emitter/waf/actions/actions.go +++ b/internal/appsec/emitter/waf/actions/actions.go @@ -25,7 +25,7 @@ var actionHandlers = map[string]actionHandler{} func registerActionHandler(aType string, handler actionHandler) { if _, ok := actionHandlers[aType]; ok { - log.Warn("appsec: action type `%s` already registered", aType) + log.Warnf("appsec: action type `%s` already registered", aType) return } actionHandlers[aType] = handler @@ -36,16 +36,16 @@ func registerActionHandler(aType string, handler actionHandler) { // When SDKError is not nil, this error is sent to the op with EmitData so that the invoked SDK can return it func SendActionEvents(op dyngo.Operation, actions map[string]any) { for aType, params := range actions { - log.Debug("appsec: processing %s action with params %v", aType, params) + log.Debugf("appsec: processing %s action with params %v", aType, params) params, ok := params.(map[string]any) if !ok { - log.Debug("appsec: could not cast action params to map[string]any from %T", params) + log.Debugf("appsec: could not cast action params to map[string]any from %T", params) continue } actionHandler, ok := actionHandlers[aType] if !ok { - log.Debug("appsec: unknown action type `%s`", aType) + log.Debugf("appsec: unknown action type `%s`", aType) continue } diff --git a/internal/appsec/emitter/waf/actions/block.go b/internal/appsec/emitter/waf/actions/block.go index ae802b60bd..2caf53b952 100644 --- a/internal/appsec/emitter/waf/actions/block.go +++ b/internal/appsec/emitter/waf/actions/block.go @@ -37,7 +37,7 @@ func init() { for env, template := range map[string]*[]byte{envBlockedTemplateJSON: &blockedTemplateJSON, envBlockedTemplateHTML: &blockedTemplateHTML} { if path, ok := os.LookupEnv(env); ok { if t, err := os.ReadFile(path); err != nil { - log.Error("Could not read template at %s: %v", path, err) + log.Errorf("Could not read template at %s: %v", path, err) } else { *template = t } diff --git a/internal/appsec/emitter/waf/run.go b/internal/appsec/emitter/waf/run.go index a77abd5b20..26a1fb6736 100644 --- a/internal/appsec/emitter/waf/run.go +++ b/internal/appsec/emitter/waf/run.go @@ -42,9 +42,9 @@ func (op *ContextOperation) Run(eventReceiver dyngo.Operation, addrs waf.RunAddr result, err := ctx.Run(addrs) if errors.Is(err, wafErrors.ErrTimeout) { - log.Debug("appsec: WAF timeout value reached: %v", err) + log.Debugf("appsec: WAF timeout value reached: %v", err) } else if err != nil { - log.Error("appsec: unexpected WAF error: %v", err) + log.Errorf("appsec: unexpected WAF error: %v", err) } op.AddEvents(result.Events...) diff --git a/internal/appsec/features.go b/internal/appsec/features.go index ca286de742..1d73bb2465 100644 --- a/internal/appsec/features.go +++ b/internal/appsec/features.go @@ -66,8 +66,8 @@ func (a *appsec) SwapRootOperation() error { oldFeatures := a.features a.features = newFeatures - log.Debug("appsec: stopping the following features: %v", oldFeatures) - log.Debug("appsec: starting the following features: %v", newFeatures) + log.Debugf("appsec: stopping the following features: %v", oldFeatures) + log.Debugf("appsec: starting the following features: %v", newFeatures) dyngo.SwapRootOperation(newRoot) diff --git a/internal/appsec/listener/grpcsec/grpc.go b/internal/appsec/listener/grpcsec/grpc.go index 52bb2c0fb7..f86f01ab0d 100644 --- a/internal/appsec/listener/grpcsec/grpc.go +++ b/internal/appsec/listener/grpcsec/grpc.go @@ -45,7 +45,7 @@ func NewGRPCSecFeature(config *config.Config, rootOp dyngo.Operation) (listener. func (f *Feature) OnStart(op *grpcsec.HandlerOperation, args grpcsec.HandlerOperationArgs) { ipTags, clientIP := httpsec.ClientIPTags(args.Metadata, false, args.RemoteAddr) - log.Debug("appsec: http client ip detection returned `%s`", clientIP) + log.Debugf("appsec: http client ip detection returned `%s`", clientIP) op.SetStringTags(ipTags) diff --git a/internal/appsec/listener/httpsec/http.go b/internal/appsec/listener/httpsec/http.go index 08b9e853dd..db055bb852 100644 --- a/internal/appsec/listener/httpsec/http.go +++ b/internal/appsec/listener/httpsec/http.go @@ -53,7 +53,7 @@ func NewHTTPSecFeature(config *config.Config, rootOp dyngo.Operation) (listener. func (feature *Feature) OnRequest(op *httpsec.HandlerOperation, args httpsec.HandlerOperationArgs) { tags, ip := ClientIPTags(args.Headers, true, args.RemoteAddr) - log.Debug("appsec: http client ip detection returned `%s` given the http headers `%v`", ip, args.Headers) + log.Debugf("appsec: http client ip detection returned `%s` given the http headers `%v`", ip, args.Headers) op.SetStringTags(tags) headers := headersRemoveCookies(args.Headers) diff --git a/internal/appsec/listener/waf/waf.go b/internal/appsec/listener/waf/waf.go index 308eaa25d7..262be56890 100644 --- a/internal/appsec/listener/waf/waf.go +++ b/internal/appsec/listener/waf/waf.go @@ -41,7 +41,7 @@ func NewWAFFeature(cfg *config.Config, rootOp dyngo.Operation) (listener.Feature return nil, fmt.Errorf("error while loading libddwaf: %w", err) } // 2. If there is an error and the loading is ok: log as an informative error where appsec can be used - log.Error("appsec: non-critical error while loading libddwaf: %v", err) + log.Errorf("appsec: non-critical error while loading libddwaf: %v", err) } newHandle, err := wafv3.NewHandle(cfg.RulesManager.Latest, cfg.Obfuscator.KeyRegex, cfg.Obfuscator.ValueRegex) @@ -74,7 +74,7 @@ func (waf *Feature) onStart(op *waf.ContextOperation, _ waf.ContextArgs) { ctx, err := waf.handle.NewContextWithBudget(waf.timeout) if err != nil { - log.Debug("appsec: failed to create Feature context: %v", err) + log.Debugf("appsec: failed to create Feature context: %v", err) } op.SwapContext(ctx) @@ -109,7 +109,7 @@ func (waf *Feature) onFinish(op *waf.ContextOperation, _ waf.ContextRes) { AddWAFMonitoringTags(op, waf.handle.Diagnostics().Version, ctx.Stats().Metrics()) if err := SetEventSpanTags(op, op.Events()); err != nil { - log.Debug("appsec: failed to set event span tags: %v", err) + log.Debugf("appsec: failed to set event span tags: %v", err) } op.SetSerializableTags(op.Derivatives()) diff --git a/internal/appsec/remoteconfig.go b/internal/appsec/remoteconfig.go index ccf6fe7631..e98c01cc47 100644 --- a/internal/appsec/remoteconfig.go +++ b/internal/appsec/remoteconfig.go @@ -106,11 +106,11 @@ updateLoop: // Switch the base rules of the RulesManager if the config received through ASM_DD is valid var newBase config.RulesFragment if err := json.Unmarshal(newBaseData, &newBase); err != nil { - log.Debug("appsec: Remote config: could not unmarshall ASM_DD rules: %v", err) + log.Debugf("appsec: Remote config: could not unmarshall ASM_DD rules: %v", err) statuses[newBasePath] = genApplyStatus(true, err) break updateLoop } - log.Debug("appsec: Remote config: switching to %s as the base rules file", newBasePath) + log.Debugf("appsec: Remote config: switching to %s as the base rules file", newBasePath) r.ChangeBase(newBase, newBasePath) statuses[newBasePath] = genApplyStatus(true, nil) case rc.ProductASM: @@ -118,22 +118,22 @@ updateLoop: // Those entries will get merged together when the final rules are compiled // If a config gets removed, the RulesManager edit entry gets removed as well for path, data := range u { - log.Debug("appsec: Remote config: processing the %s ASM config", path) + log.Debugf("appsec: Remote config: processing the %s ASM config", path) if data == nil { - log.Debug("appsec: Remote config: ASM config %s was removed", path) + log.Debugf("appsec: Remote config: ASM config %s was removed", path) r.RemoveEdit(path) continue } var f config.RulesFragment if err = json.Unmarshal(data, &f); err != nil { - log.Debug("appsec: Remote config: error processing ASM config %s: %v", path, err) + log.Debugf("appsec: Remote config: error processing ASM config %s: %v", path, err) statuses[path] = genApplyStatus(true, err) break updateLoop } r.AddEdit(path, f) } default: - log.Debug("appsec: Remote config: ignoring unsubscribed product %s", p) + log.Debugf("appsec: Remote config: ignoring unsubscribed product %s", p) } } @@ -169,13 +169,13 @@ func (a *appsec) onRCRulesUpdate(updates map[string]remoteconfig.ProductUpdate) r := a.cfg.RulesManager.Clone() statuses, err := combineRCRulesUpdates(&r, updates) if err != nil { - log.Debug("appsec: Remote config: not applying any updates because of error: %v", err) + log.Debugf("appsec: Remote config: not applying any updates because of error: %v", err) return statuses } // Compile the final rules once all updates have been processed and no error occurred r.Compile() - log.Debug("appsec: Remote config: final compiled rules: %s", r.String()) + log.Debugf("appsec: Remote config: final compiled rules: %s", r.String()) // Replace the RulesManager with the new one holding the new state a.cfg.RulesManager = &r @@ -183,7 +183,7 @@ func (a *appsec) onRCRulesUpdate(updates map[string]remoteconfig.ProductUpdate) // If an error occurs while updating the WAF handle, don't swap the RulesManager and propagate the error // to all config statuses since we can't know which config is the faulty one if err = a.SwapRootOperation(); err != nil { - log.Error("appsec: Remote config: could not apply the new security rules: %v", err) + log.Errorf("appsec: Remote config: could not apply the new security rules: %v", err) for k := range statuses { statuses[k] = genApplyStatus(true, err) } @@ -198,14 +198,14 @@ func (a *appsec) onRCRulesUpdate(updates map[string]remoteconfig.ProductUpdate) func (a *appsec) handleASMFeatures(u remoteconfig.ProductUpdate) map[string]rc.ApplyStatus { statuses := statusesFromUpdate(u, false, nil) if l := len(u); l > 1 { - log.Error("appsec: Remote config: %d configs received for ASM_FEATURES. Expected one at most, returning early", l) + log.Errorf("appsec: Remote config: %d configs received for ASM_FEATURES. Expected one at most, returning early", l) return statuses } for path, raw := range u { var data rc.ASMFeaturesData status := rc.ApplyStatus{State: rc.ApplyStateAcknowledged} var err error - log.Debug("appsec: Remote config: processing %s", path) + log.Debugf("appsec: Remote config: processing %s", path) // A nil config means ASM was disabled, and we stopped receiving the config file // Don't ack the config in this case and return early @@ -215,13 +215,13 @@ func (a *appsec) handleASMFeatures(u remoteconfig.ProductUpdate) map[string]rc.A return statuses } if err = json.Unmarshal(raw, &data); err != nil { - log.Error("appsec: Remote config: error while unmarshalling %s: %v. Configuration won't be applied.", path, err) + log.Errorf("appsec: Remote config: error while unmarshalling %s: %v. Configuration won't be applied.", path, err) } else if data.ASM.Enabled && !a.started { log.Debug("appsec: Remote config: Starting AppSec") telemetry := newAppsecTelemetry() defer telemetry.emit() if err = a.start(telemetry); err != nil { - log.Error("appsec: Remote config: error while processing %s. Configuration won't be applied: %v", path, err) + log.Errorf("appsec: Remote config: error while processing %s. Configuration won't be applied: %v", path, err) } } else if !data.ASM.Enabled && a.started { log.Debug("appsec: Remote config: Stopping AppSec") @@ -272,12 +272,12 @@ func mergeASMDataUpdates(u remoteconfig.ProductUpdate) (config.RulesFragment, ma } for path, raw := range u { - log.Debug("appsec: Remote config: processing %s", path) + log.Debugf("appsec: Remote config: processing %s", path) // A nil config means ASM_DATA was disabled, and we stopped receiving the config file // Don't ack the config in this case if raw == nil { - log.Debug("appsec: remote config: %s disabled", path) + log.Debugf("appsec: remote config: %s disabled", path) statuses[path] = genApplyStatus(false, nil) continue } @@ -287,7 +287,7 @@ func mergeASMDataUpdates(u remoteconfig.ProductUpdate) (config.RulesFragment, ma ExclusionData []config.DataEntry `json:"exclusion_data,omitempty"` } if err := json.Unmarshal(raw, &asmdataUpdate); err != nil { - log.Debug("appsec: Remote config: error while unmarshalling payload for %s: %v. Configuration won't be applied.", path, err) + log.Debugf("appsec: Remote config: error while unmarshalling payload for %s: %v. Configuration won't be applied.", path, err) statuses[path] = genApplyStatus(false, err) continue } @@ -404,24 +404,24 @@ func (a *appsec) enableRCBlocking() { return } if _, isSet := os.LookupEnv(internal.EnvRules); isSet { - log.Debug("appsec: Remote config: using rules from %s, blocking capabilities won't be enabled", a.cfg.RulesManager.BasePath) + log.Debugf("appsec: Remote config: using rules from %s, blocking capabilities won't be enabled", a.cfg.RulesManager.BasePath) return } products := []string{rc.ProductASM, rc.ProductASMDD, rc.ProductASMData} for _, p := range products { if err := a.registerRCProduct(p); err != nil { - log.Debug("appsec: Remote config: couldn't register product %s: %v", p, err) + log.Debugf("appsec: Remote config: couldn't register product %s: %v", p, err) } } if err := remoteconfig.RegisterCallback(a.onRCRulesUpdate); err != nil { - log.Debug("appsec: Remote config: couldn't register callback: %v", err) + log.Debugf("appsec: Remote config: couldn't register callback: %v", err) } for _, c := range blockingCapabilities { if err := a.registerRCCapability(c); err != nil { - log.Debug("appsec: Remote config: couldn't register capability %v: %v", c, err) + log.Debugf("appsec: Remote config: couldn't register capability %v: %v", c, err) } } } @@ -431,14 +431,14 @@ func (a *appsec) enableRASP() { return } if err := remoteconfig.RegisterCapability(remoteconfig.ASMRASPSSRF); err != nil { - log.Debug("appsec: Remote config: couldn't register RASP SSRF: %v", err) + log.Debugf("appsec: Remote config: couldn't register RASP SSRF: %v", err) } if err := remoteconfig.RegisterCapability(remoteconfig.ASMRASPSQLI); err != nil { - log.Debug("appsec: Remote config: couldn't register RASP SQLI: %v", err) + log.Debugf("appsec: Remote config: couldn't register RASP SQLI: %v", err) } if orchestrion.Enabled() { if err := remoteconfig.RegisterCapability(remoteconfig.ASMRASPLFI); err != nil { - log.Debug("appsec: Remote config: couldn't register RASP LFI: %v", err) + log.Debugf("appsec: Remote config: couldn't register RASP LFI: %v", err) } } } @@ -449,10 +449,10 @@ func (a *appsec) disableRCBlocking() { } for _, c := range blockingCapabilities { if err := a.unregisterRCCapability(c); err != nil { - log.Debug("appsec: Remote config: couldn't unregister capability %v: %v", c, err) + log.Debugf("appsec: Remote config: couldn't unregister capability %v: %v", c, err) } } if err := remoteconfig.UnregisterCallback(a.onRCRulesUpdate); err != nil { - log.Debug("appsec: Remote config: couldn't unregister callback: %v", err) + log.Debugf("appsec: Remote config: couldn't unregister callback: %v", err) } } diff --git a/internal/civisibility/integrations/civisibility_features.go b/internal/civisibility/integrations/civisibility_features.go index 91379c31a2..8765868fff 100644 --- a/internal/civisibility/integrations/civisibility_features.go +++ b/internal/civisibility/integrations/civisibility_features.go @@ -77,9 +77,9 @@ func ensureSettingsInitialization(serviceName string) { go func() { bytes, err := uploadRepositoryChanges() if err != nil { - log.Error("civisibility: error uploading repository changes: %v", err) + log.Errorf("civisibility: error uploading repository changes: %v", err) } else { - log.Debug("civisibility: uploaded %v bytes in pack files", bytes) + log.Debugf("civisibility: uploaded %v bytes in pack files", bytes) } uploadChannel <- struct{}{} }() @@ -87,7 +87,7 @@ func ensureSettingsInitialization(serviceName string) { // Get the CI Visibility settings payload for this test session ciSettings, err := ciVisibilityClient.GetSettings() if err != nil { - log.Error("civisibility: error getting CI visibility settings: %v", err) + log.Errorf("civisibility: error getting CI visibility settings: %v", err) } else if ciSettings != nil { ciVisibilitySettings = *ciSettings } @@ -98,7 +98,7 @@ func ensureSettingsInitialization(serviceName string) { <-uploadChannel ciSettings, err = ciVisibilityClient.GetSettings() if err != nil { - log.Error("civisibility: error getting CI visibility settings: %v", err) + log.Errorf("civisibility: error getting CI visibility settings: %v", err) } else if ciSettings != nil { ciVisibilitySettings = *ciSettings } @@ -125,7 +125,7 @@ func ensureAdditionalFeaturesInitialization(serviceName string) { if ciVisibilitySettings.EarlyFlakeDetection.Enabled { ciEfdData, err := ciVisibilityClient.GetEarlyFlakeDetectionData() if err != nil { - log.Error("civisibility: error getting CI visibility early flake detection data: %v", err) + log.Errorf("civisibility: error getting CI visibility early flake detection data: %v", err) } else if ciEfdData != nil { ciVisibilityEarlyFlakyDetectionSettings = *ciEfdData log.Debug("civisibility: early flake detection data loaded.") @@ -143,7 +143,7 @@ func ensureAdditionalFeaturesInitialization(serviceName string) { TotalRetryCount: totalRetriesCount, RemainingTotalRetryCount: totalRetriesCount, } - log.Debug("civisibility: automatic test retries enabled [retryCount: %v, totalRetryCount: %v]", retryCount, totalRetriesCount) + log.Debugf("civisibility: automatic test retries enabled [retryCount: %v, totalRetryCount: %v]", retryCount, totalRetriesCount) } else { log.Warn("civisibility: flaky test retries was disabled by the environment variable") ciVisibilitySettings.FlakyTestRetriesEnabled = false @@ -155,9 +155,9 @@ func ensureAdditionalFeaturesInitialization(serviceName string) { // get the skippable tests correlationId, skippableTests, err := ciVisibilityClient.GetSkippableTests() if err != nil { - log.Error("civisibility: error getting CI visibility skippable tests: %v", err) + log.Errorf("civisibility: error getting CI visibility skippable tests: %v", err) } else if skippableTests != nil { - log.Debug("civisibility: skippable tests loaded: %d suites", len(skippableTests)) + log.Debugf("civisibility: skippable tests loaded: %d suites", len(skippableTests)) utils.AddCITags(constants.ItrCorrelationIDTag, correlationId) ciVisibilitySkippables = skippableTests } @@ -256,7 +256,7 @@ func getSearchCommits() (*searchCommitsResponse, error) { return newSearchCommitsResponse(nil, nil, false), nil } - log.Debug("civisibility: local commits found: %d", len(localCommits)) + log.Debugf("civisibility: local commits found: %d", len(localCommits)) remoteCommits, err := ciVisibilityClient.GetCommits(localCommits) return newSearchCommitsResponse(localCommits, remoteCommits, true), err } @@ -296,7 +296,7 @@ func sendObjectsPackFile(commitSha string, commitsToInclude []string, commitsToE } // send the pack files - log.Debug("civisibility: sending pack file with missing commits. files: %v", packFiles) + log.Debugf("civisibility: sending pack file with missing commits. files: %v", packFiles) // try to remove the pack files after sending them defer func(files []string) { diff --git a/internal/civisibility/integrations/gotesting/coverage/coverage_payload.go b/internal/civisibility/integrations/gotesting/coverage/coverage_payload.go index 2abc192897..4cbd9b791a 100644 --- a/internal/civisibility/integrations/gotesting/coverage/coverage_payload.go +++ b/internal/civisibility/integrations/gotesting/coverage/coverage_payload.go @@ -147,7 +147,7 @@ func (p *coveragePayload) Read(b []byte) (n int, err error) { // An error if reading from the buffer or encoding the payload fails. func (p *coveragePayload) getBuffer() (*bytes.Buffer, error) { startTime := time.Now() - log.Debug("coveragePayload: .getBuffer (count: %v)", p.itemCount()) + log.Debugf("coveragePayload: .getBuffer (count: %v)", p.itemCount()) // Create a buffer to read the current payload payloadBuf := new(bytes.Buffer) diff --git a/internal/civisibility/integrations/gotesting/coverage/coverage_writer.go b/internal/civisibility/integrations/gotesting/coverage/coverage_writer.go index c5e123e518..fedbd92c28 100644 --- a/internal/civisibility/integrations/gotesting/coverage/coverage_writer.go +++ b/internal/civisibility/integrations/gotesting/coverage/coverage_writer.go @@ -48,7 +48,7 @@ func (w *coverageWriter) add(coverage *testCoverage) { telemetry.EventsEnqueueForSerialization() ciTestCoverage := newCiTestCoverageData(coverage) if err := w.payload.push(ciTestCoverage); err != nil { - log.Error("coverageWriter: Error encoding msgpack: %v", err) + log.Errorf("coverageWriter: Error encoding msgpack: %v", err) } if w.payload.size() > agentlessPayloadSizeLimit { w.flush() @@ -84,18 +84,18 @@ func (w *coverageWriter) flush() { }() size, count := p.size(), p.itemCount() - log.Debug("coverageWriter: sending payload: size: %d events: %d\n", size, count) + log.Debugf("coverageWriter: sending payload: size: %d events: %d\n", size, count) buf, err := p.getBuffer() if err != nil { - log.Error("coverageWriter: failure getting coverage data: %v", err) + log.Errorf("coverageWriter: failure getting coverage data: %v", err) return } telemetry.CodeCoverageFiles(float64(p.itemCount())) err = w.client.SendCoveragePayload(buf) if err != nil { - log.Error("coverageWriter: failure sending coverage data: %v", err) + log.Errorf("coverageWriter: failure sending coverage data: %v", err) } }(oldp) } diff --git a/internal/civisibility/integrations/gotesting/coverage/test_coverage.go b/internal/civisibility/integrations/gotesting/coverage/test_coverage.go index 8b1afa9eaf..8f7e1dcc42 100644 --- a/internal/civisibility/integrations/gotesting/coverage/test_coverage.go +++ b/internal/civisibility/integrations/gotesting/coverage/test_coverage.go @@ -91,7 +91,7 @@ func InitializeCoverage(m *testing.M) { log.Debug("civisibility.coverage: initializing runtime coverage") testDep, err := getTestDepsCoverage(m) if err != nil || testDep == nil { - log.Debug("civisibility.coverage: error initializing runtime coverage: %v", err) + log.Debugf("civisibility.coverage: error initializing runtime coverage: %v", err) return } @@ -124,9 +124,9 @@ func InitializeCoverage(m *testing.M) { // create a temporary directory to store coverage files temporaryDir, err = os.MkdirTemp("", "coverage") if err != nil { - log.Debug("civisibility.coverage: error creating temporary directory: %v", err) + log.Debugf("civisibility.coverage: error creating temporary directory: %v", err) } else { - log.Debug("civisibility.coverage: temporary coverage directory created: %s", temporaryDir) + log.Debugf("civisibility.coverage: temporary coverage directory created: %s", temporaryDir) } integrations.PushCiVisibilityCloseAction(func() { _ = os.RemoveAll(temporaryDir) @@ -135,7 +135,7 @@ func InitializeCoverage(m *testing.M) { // executing go list -f '{{.Module.Path}};{{.Module.Dir}}' to get the module path and module dir stdOut, err := exec.Command("go", "list", "-f", "{{.Module.Path}};{{.Module.Dir}}").CombinedOutput() if err != nil { - log.Debug("civisibility.coverage: error getting module path and module dir: %v", err) + log.Debugf("civisibility.coverage: error getting module path and module dir: %v", err) } else { parts := strings.Split(string(stdOut), ";") if len(parts) == 2 { @@ -159,19 +159,19 @@ func GetCoverage() float64 { coverageFile := filepath.Join(temporaryDir, "global_coverage.out") _, err := tearDown(coverageFile, "") if err != nil { - log.Debug("civisibility.coverage: error getting coverage file: %v", err) + log.Debugf("civisibility.coverage: error getting coverage file: %v", err) } defer func(cFile string) { err = os.Remove(cFile) if err != nil { - log.Debug("civisibility.coverage: error removing coverage file: %v", err) + log.Debugf("civisibility.coverage: error removing coverage file: %v", err) } }(coverageFile) totalStatements, coveredStatements, err := getCoverageStatementsInfo(coverageFile) if err != nil { - log.Debug("civisibility.coverage: error parsing coverage file: %v", err) + log.Debugf("civisibility.coverage: error parsing coverage file: %v", err) } if totalStatements == 0 { @@ -202,7 +202,7 @@ func (t *testCoverage) CollectCoverageBeforeTestExecution() { t.preCoverageFilename = filepath.Join(temporaryDir, fmt.Sprintf("%d-%d-%d-pre.out", t.moduleID, t.suiteID, t.testID)) _, err := tearDown(t.preCoverageFilename, "") if err != nil { - log.Debug("civisibility.coverage: error getting coverage file: %v", err) + log.Debugf("civisibility.coverage: error getting coverage file: %v", err) telemetry.CodeCoverageErrors() } else { telemetry.CodeCoverageStarted(testFramework, telemetry.DefaultCoverageLibraryType) @@ -218,7 +218,7 @@ func (t *testCoverage) CollectCoverageAfterTestExecution() { t.postCoverageFilename = filepath.Join(temporaryDir, fmt.Sprintf("%d-%d-%d-post.out", t.moduleID, t.suiteID, t.testID)) _, err := tearDown(t.postCoverageFilename, "") if err != nil { - log.Debug("civisibility.coverage: error getting coverage file: %v", err) + log.Debugf("civisibility.coverage: error getting coverage file: %v", err) telemetry.CodeCoverageErrors() } @@ -243,13 +243,13 @@ func (t *testCoverage) processCoverageData() { } preCoverage, err := parseCoverProfile(t.preCoverageFilename) if err != nil { - log.Debug("civisibility.coverage: error parsing pre-coverage file: %v", err) + log.Debugf("civisibility.coverage: error parsing pre-coverage file: %v", err) telemetry.CodeCoverageErrors() return } postCoverage, err := parseCoverProfile(t.postCoverageFilename) if err != nil { - log.Debug("civisibility.coverage: error parsing post-coverage file: %v", err) + log.Debugf("civisibility.coverage: error parsing post-coverage file: %v", err) telemetry.CodeCoverageErrors() return } @@ -264,12 +264,12 @@ func (t *testCoverage) processCoverageData() { err = os.Remove(t.preCoverageFilename) if err != nil { - log.Debug("civisibility.coverage: error removing pre-coverage file: %v", err) + log.Debugf("civisibility.coverage: error removing pre-coverage file: %v", err) } err = os.Remove(t.postCoverageFilename) if err != nil { - log.Debug("civisibility.coverage: error removing post-coverage file: %v", err) + log.Debugf("civisibility.coverage: error removing post-coverage file: %v", err) } } diff --git a/internal/civisibility/utils/ci_providers.go b/internal/civisibility/utils/ci_providers.go index 5899929f7b..6f186bffa1 100644 --- a/internal/civisibility/utils/ci_providers.go +++ b/internal/civisibility/utils/ci_providers.go @@ -80,9 +80,9 @@ func getProviderTags() map[string]string { if log.DebugEnabled() { if providerName, ok := tags[constants.CIProviderName]; ok { - log.Debug("civisibility: detected ci provider: %v", providerName) + log.Debugf("civisibility: detected ci provider: %v", providerName) } else { - log.Debug("civisibility: no ci provider was detected.") + log.Debugf("civisibility: no ci provider was detected.") } } diff --git a/internal/civisibility/utils/codeowners.go b/internal/civisibility/utils/codeowners.go index 0674945151..68d4072bbb 100644 --- a/internal/civisibility/utils/codeowners.go +++ b/internal/civisibility/utils/codeowners.go @@ -77,11 +77,11 @@ func GetCodeOwners() *CodeOwners { codeowners, err = NewCodeOwners(path) if err == nil { if logger.DebugEnabled() { - logger.Debug("civisibility: codeowner file '%v' was loaded successfully.", path) + logger.Debugf("civisibility: codeowner file '%v' was loaded successfully.", path) } return codeowners } - logger.Debug("Error parsing codeowners: %s", err) + logger.Debugf("Error parsing codeowners: %s", err) } } } @@ -103,7 +103,7 @@ func NewCodeOwners(filePath string) (*CodeOwners, error) { defer func() { err = file.Close() if err != nil && !errors.Is(os.ErrClosed, err) { - logger.Warn("Error closing codeowners file: %s", err.Error()) + logger.Warnf("Error closing codeowners file: %s", err.Error()) } }() diff --git a/internal/civisibility/utils/environmentTags.go b/internal/civisibility/utils/environmentTags.go index 9a14bcbf79..d7c720324f 100644 --- a/internal/civisibility/utils/environmentTags.go +++ b/internal/civisibility/utils/environmentTags.go @@ -122,9 +122,9 @@ func createCITagsMap() map[string]string { localTags[constants.OSArchitecture] = runtime.GOARCH localTags[constants.RuntimeName] = runtime.Compiler localTags[constants.RuntimeVersion] = runtime.Version() - log.Debug("civisibility: os platform: %v", runtime.GOOS) - log.Debug("civisibility: os architecture: %v", runtime.GOARCH) - log.Debug("civisibility: runtime version: %v", runtime.Version()) + log.Debugf("civisibility: os platform: %v", runtime.GOOS) + log.Debugf("civisibility: os architecture: %v", runtime.GOARCH) + log.Debugf("civisibility: runtime version: %v", runtime.Version()) // Get command line test command var cmd string @@ -140,7 +140,7 @@ func createCITagsMap() map[string]string { cmd = regexp.MustCompile(`(?si)-test.testlogfile=(.*)\s`).ReplaceAllString(cmd, "") cmd = strings.TrimSpace(cmd) localTags[constants.TestCommand] = cmd - log.Debug("civisibility: test command: %v", cmd) + log.Debugf("civisibility: test command: %v", cmd) // Populate the test session name if testSessionName, ok := os.LookupEnv(constants.CIVisibilityTestSessionNameEnvironmentVariable); ok { @@ -150,7 +150,7 @@ func createCITagsMap() map[string]string { } else { localTags[constants.TestSessionName] = cmd } - log.Debug("civisibility: test session name: %v", localTags[constants.TestSessionName]) + log.Debugf("civisibility: test session name: %v", localTags[constants.TestSessionName]) // Check if the user provided the test service if ddService := os.Getenv("DD_SERVICE"); ddService != "" { @@ -201,8 +201,8 @@ func createCITagsMap() map[string]string { } } - log.Debug("civisibility: workspace directory: %v", localTags[constants.CIWorkspacePath]) - log.Debug("civisibility: common tags created with %v items", len(localTags)) + log.Debugf("civisibility: workspace directory: %v", localTags[constants.CIWorkspacePath]) + log.Debugf("civisibility: common tags created with %v items", len(localTags)) return localTags } @@ -215,6 +215,6 @@ func createCIMetricsMap() map[string]float64 { localMetrics := make(map[string]float64) localMetrics[constants.LogicalCPUCores] = float64(runtime.NumCPU()) - log.Debug("civisibility: common metrics created with %v items", len(localMetrics)) + log.Debugf("civisibility: common metrics created with %v items", len(localMetrics)) return localMetrics } diff --git a/internal/civisibility/utils/git.go b/internal/civisibility/utils/git.go index a1f250f62e..3ee2fe7682 100644 --- a/internal/civisibility/utils/git.go +++ b/internal/civisibility/utils/git.go @@ -175,9 +175,9 @@ func getLocalGitData() (localGitData, error) { // Ensure we have permissions to read the git directory if currentDir, err := os.Getwd(); err == nil { if gitDir, err := getParentGitFolder(currentDir); err == nil && gitDir != "" { - log.Debug("civisibility.git: setting permissions to git folder: %s", gitDir) + log.Debugf("civisibility.git: setting permissions to git folder: %s", gitDir) if out, err := execGitString(telemetry.NotSpecifiedCommandsType, "config", "--global", "--add", "safe.directory", gitDir); err != nil { - log.Debug("civisibility.git: error while setting permissions to git folder: %s\n%s\n%s", gitDir, err.Error(), out) + log.Debugf("civisibility.git: error while setting permissions to git folder: %s\n%s\n%s", gitDir, err.Error(), out) } } else { log.Debug("civisibility.git: error getting the parent git folder.") @@ -282,7 +282,7 @@ func UnshallowGitRepository() (bool, error) { if err != nil { return false, fmt.Errorf("civisibility.unshallow: error getting the git version: %s", err.Error()) } - log.Debug("civisibility.unshallow: git version: %v.%v.%v", major, minor, patch) + log.Debugf("civisibility.unshallow: git version: %v.%v.%v", major, minor, patch) if major < 2 || (major == 2 && minor < 27) { log.Debug("civisibility.unshallow: the git version is less than 2.27.0 we cannot unshallow the repository") return false, nil @@ -300,7 +300,7 @@ func UnshallowGitRepository() (bool, error) { // if the origin name is empty, we fallback to "origin" originName = "origin" } - log.Debug("civisibility.unshallow: origin name: %v", originName) + log.Debugf("civisibility.unshallow: origin name: %v", originName) // let's get the sha of the HEAD (git rev-parse HEAD) headSha, err := execGitString(telemetry.GetHeadCommandsType, "rev-parse", "HEAD") @@ -314,7 +314,7 @@ func UnshallowGitRepository() (bool, error) { return false, fmt.Errorf("civisibility.unshallow: error getting the current branch: %s\n%s", err.Error(), headSha) } } - log.Debug("civisibility.unshallow: HEAD sha: %v", headSha) + log.Debugf("civisibility.unshallow: HEAD sha: %v", headSha) // let's fetch the missing commits and trees from the last month // git fetch --shallow-since="1 month ago" --update-shallow --filter="blob:none" --recurse-submodules=no $(git config --default origin --get clone.defaultRemoteName) $(git rev-parse HEAD) @@ -323,7 +323,7 @@ func UnshallowGitRepository() (bool, error) { // let's check if the last command was unsuccessful if err != nil || fetchOutput == "" { - log.Debug("civisibility.unshallow: error fetching the missing commits and trees from the last month: %v", err) + log.Debugf("civisibility.unshallow: error fetching the missing commits and trees from the last month: %v", err) // *** // The previous command has a drawback: if the local HEAD is a commit that has not been pushed to the remote, it will fail. // If this is the case, we fallback to: `git fetch --shallow-since="1 month ago" --update-shallow --filter="blob:none" --recurse-submodules=no $(git config --default origin --get clone.defaultRemoteName) $(git rev-parse --abbrev-ref --symbolic-full-name @{upstream})` @@ -343,7 +343,7 @@ func UnshallowGitRepository() (bool, error) { // let's check if the last command was unsuccessful if err != nil || fetchOutput == "" { - log.Debug("civisibility.unshallow: error fetching the missing commits and trees from the last month: %v", err) + log.Debugf("civisibility.unshallow: error fetching the missing commits and trees from the last month: %v", err) // *** // It could be that the CI is working on a detached HEAD or maybe branch tracking hasn’t been set up. // In that case, this command will also fail, and we will finally fallback to we just unshallow all the things: @@ -432,7 +432,7 @@ func CreatePackFiles(commitsToInclude []string, commitsToExclude []string) []str // get a temporary path to store the pack files temporaryPath, err := os.MkdirTemp("", "pack-objects") if err != nil { - log.Warn("civisibility: error creating temporary directory: %s", err) + log.Warnf("civisibility: error creating temporary directory: %s", err) return nil } @@ -440,7 +440,7 @@ func CreatePackFiles(commitsToInclude []string, commitsToExclude []string) []str out, err := execGitStringWithInput(telemetry.PackObjectsCommandsType, objectsShasString, "pack-objects", "--compression=9", "--max-pack-size="+strconv.Itoa(MaxPackFileSizeInMb)+"m", temporaryPath+"/") if err != nil { - log.Warn("civisibility: error creating pack files: %s", err) + log.Warnf("civisibility: error creating pack files: %s", err) return nil } @@ -451,7 +451,7 @@ func CreatePackFiles(commitsToInclude []string, commitsToExclude []string) []str // check if the pack file exists if _, err := os.Stat(file); os.IsNotExist(err) { - log.Warn("civisibility: pack file not found: %s", packFiles[i]) + log.Warnf("civisibility: pack file not found: %s", packFiles[i]) continue } diff --git a/internal/civisibility/utils/home.go b/internal/civisibility/utils/home.go index fd2000c893..de7c21147d 100644 --- a/internal/civisibility/utils/home.go +++ b/internal/civisibility/utils/home.go @@ -59,7 +59,7 @@ func ExpandPath(path string) string { // The home directory of the current user. func getHomeDir() (homeDir string) { defer func() { - log.Debug("civisibility: home directory: %v", homeDir) + log.Debugf("civisibility: home directory: %v", homeDir) }() if runtime.GOOS == "windows" { diff --git a/internal/civisibility/utils/net/client.go b/internal/civisibility/utils/net/client.go index c1aeb15389..470877067b 100644 --- a/internal/civisibility/utils/net/client.go +++ b/internal/civisibility/utils/net/client.go @@ -199,7 +199,7 @@ func NewClientWithServiceNameAndSubdomain(serviceName, subdomain string) Client defaultHeaders["trace_id"] = id defaultHeaders["parent_id"] = id - log.Debug("ciVisibilityHttpClient: new client created [id: %v, agentless: %v, url: %v, env: %v, serviceName: %v, subdomain: %v]", + log.Debugf("ciVisibilityHttpClient: new client created [id: %v, agentless: %v, url: %v, env: %v, serviceName: %v, subdomain: %v]", id, agentlessEnabled, baseURL, environment, serviceName, subdomain) if !telemetry.Disabled() { diff --git a/internal/civisibility/utils/net/http.go b/internal/civisibility/utils/net/http.go index 71c402cd16..05f9333814 100644 --- a/internal/civisibility/utils/net/http.go +++ b/internal/civisibility/utils/net/http.go @@ -152,7 +152,7 @@ func (rh *RequestHandler) internalSendRequest(config *RequestConfig, attempt int for _, f := range config.Files { files = append(files, f.FieldName) } - log.Debug("ciVisibilityHttpClient: new request with files [method: %v, url: %v, attempt: %v, maxRetries: %v] %v", + log.Debugf("ciVisibilityHttpClient: new request with files [method: %v, url: %v, attempt: %v, maxRetries: %v] %v", config.Method, config.URL, attempt, config.MaxRetries, files) } req, err = http.NewRequest(config.Method, config.URL, bytes.NewBuffer(body)) @@ -171,7 +171,7 @@ func (rh *RequestHandler) internalSendRequest(config *RequestConfig, attempt int } if log.DebugEnabled() { - log.Debug("ciVisibilityHttpClient: new request with body [method: %v, url: %v, attempt: %v, maxRetries: %v, compressed: %v] %v bytes", + log.Debugf("ciVisibilityHttpClient: new request with body [method: %v, url: %v, attempt: %v, maxRetries: %v, compressed: %v] %v bytes", config.Method, config.URL, attempt, config.MaxRetries, config.Compressed, len(serializedBody)) } @@ -204,7 +204,7 @@ func (rh *RequestHandler) internalSendRequest(config *RequestConfig, attempt int return true, nil, err } - log.Debug("ciVisibilityHttpClient: new request [method: %v, url: %v, attempt: %v, maxRetries: %v]", + log.Debugf("ciVisibilityHttpClient: new request [method: %v, url: %v, attempt: %v, maxRetries: %v]", config.Method, config.URL, attempt, config.MaxRetries) } @@ -218,7 +218,7 @@ func (rh *RequestHandler) internalSendRequest(config *RequestConfig, attempt int resp, err := rh.Client.Do(req) if err != nil { - log.Debug("ciVisibilityHttpClient: error = %v", err) + log.Debugf("ciVisibilityHttpClient: error = %v", err) // Retry if there's an error exponentialBackoff(attempt, config.Backoff) return false, nil, nil @@ -231,7 +231,7 @@ func (rh *RequestHandler) internalSendRequest(config *RequestConfig, attempt int // Check for rate-limiting (HTTP 429) if resp.StatusCode == HTTPStatusTooManyRequests { - log.Debug("ciVisibilityHttpClient: response status code = %v", resp.StatusCode) + log.Debugf("ciVisibilityHttpClient: response status code = %v", resp.StatusCode) rateLimitReset := resp.Header.Get(HeaderRateLimitReset) if rateLimitReset != "" { @@ -259,7 +259,7 @@ func (rh *RequestHandler) internalSendRequest(config *RequestConfig, attempt int // Check status code for retries if statusCode >= 406 { // Retry if the status code is >= 406 - log.Debug("ciVisibilityHttpClient: response status code = %v", resp.StatusCode) + log.Debugf("ciVisibilityHttpClient: response status code = %v", resp.StatusCode) exponentialBackoff(attempt, config.Backoff) return false, nil, nil } @@ -289,7 +289,7 @@ func (rh *RequestHandler) internalSendRequest(config *RequestConfig, attempt int } if log.DebugEnabled() { - log.Debug("ciVisibilityHttpClient: response received [method: %v, url: %v, status_code: %v, format: %v] %v bytes", + log.Debugf("ciVisibilityHttpClient: response received [method: %v, url: %v, status_code: %v, format: %v] %v bytes", config.Method, config.URL, resp.StatusCode, responseFormat, len(responseBody)) } diff --git a/internal/civisibility/utils/net/settings_api.go b/internal/civisibility/utils/net/settings_api.go index aa2f88dc66..49b190dae4 100644 --- a/internal/civisibility/utils/net/settings_api.go +++ b/internal/civisibility/utils/net/settings_api.go @@ -107,7 +107,7 @@ func (c *client) GetSettings() (*SettingsResponseData, error) { } if log.DebugEnabled() { - log.Debug("civisibility.settings: %s", string(response.Body)) + log.Debugf("civisibility.settings: %s", string(response.Body)) } var settingsResponseType telemetry.SettingsResponseType diff --git a/internal/datastreams/processor.go b/internal/datastreams/processor.go index 10a8b8afb3..a4d7c90fdf 100644 --- a/internal/datastreams/processor.go +++ b/internal/datastreams/processor.go @@ -80,17 +80,17 @@ func (b bucket) export(timestampType TimestampType) StatsBucket { for _, s := range b.points { pathwayLatency, err := proto.Marshal(s.pathwayLatency.ToProto()) if err != nil { - log.Error("can't serialize pathway latency. Ignoring: %v", err) + log.Errorf("can't serialize pathway latency. Ignoring: %v", err) continue } edgeLatency, err := proto.Marshal(s.edgeLatency.ToProto()) if err != nil { - log.Error("can't serialize edge latency. Ignoring: %v", err) + log.Errorf("can't serialize edge latency. Ignoring: %v", err) continue } payloadSize, err := proto.Marshal(s.payloadSize.ToProto()) if err != nil { - log.Error("can't serialize payload size. Ignoring: %v", err) + log.Errorf("can't serialize payload size. Ignoring: %v", err) continue } stats = append(stats, StatsPoint{ @@ -247,13 +247,13 @@ func (p *Processor) addToBuckets(point statsPoint, btime int64, buckets map[int6 b.points[point.hash] = group } if err := group.pathwayLatency.Add(math.Max(float64(point.pathwayLatency)/float64(time.Second), 0)); err != nil { - log.Error("failed to add pathway latency. Ignoring %v.", err) + log.Errorf("failed to add pathway latency. Ignoring %v.", err) } if err := group.edgeLatency.Add(math.Max(float64(point.edgeLatency)/float64(time.Second), 0)); err != nil { - log.Error("failed to add edge latency. Ignoring %v.", err) + log.Errorf("failed to add edge latency. Ignoring %v.", err) } if err := group.payloadSize.Add(float64(point.payloadSize)); err != nil { - log.Error("failed to add payload size. Ignoring %v.", err) + log.Errorf("failed to add payload size. Ignoring %v.", err) } } diff --git a/internal/env.go b/internal/env.go index 62704b7792..7d46c0c6de 100644 --- a/internal/env.go +++ b/internal/env.go @@ -23,7 +23,7 @@ func BoolEnv(key string, def bool) bool { } v, err := strconv.ParseBool(vv) if err != nil { - log.Warn("Non-boolean value for env var %s, defaulting to %t. Parse failed with error: %v", key, def, err) + log.Warnf("Non-boolean value for env var %s, defaulting to %t. Parse failed with error: %v", key, def, err) return def } return v @@ -38,7 +38,7 @@ func IntEnv(key string, def int) int { } v, err := strconv.Atoi(vv) if err != nil { - log.Warn("Non-integer value for env var %s, defaulting to %d. Parse failed with error: %v", key, def, err) + log.Warnf("Non-integer value for env var %s, defaulting to %d. Parse failed with error: %v", key, def, err) return def } return v @@ -53,7 +53,7 @@ func DurationEnv(key string, def time.Duration) time.Duration { } v, err := time.ParseDuration(vv) if err != nil { - log.Warn("Non-duration value for env var %s, defaulting to %d. Parse failed with error: %v", key, def, err) + log.Warnf("Non-duration value for env var %s, defaulting to %d. Parse failed with error: %v", key, def, err) return def } return v @@ -102,7 +102,7 @@ func FloatEnv(key string, def float64) float64 { } v, err := strconv.ParseFloat(env, 64) if err != nil { - log.Warn("Non-float value for env var %s, defaulting to %f. Parse failed with error: %v", key, def, err) + log.Warnf("Non-float value for env var %s, defaulting to %f. Parse failed with error: %v", key, def, err) return def } return v diff --git a/internal/gitmetadata.go b/internal/gitmetadata.go index ce0ea38e57..32c38078f8 100644 --- a/internal/gitmetadata.go +++ b/internal/gitmetadata.go @@ -93,7 +93,7 @@ func getTagsFromBinary(readBuildInfo func() (*debug.BuildInfo, bool)) map[string } } if vcs != "git" { - log.Debug("Unknown VCS: '%s', skip source code metadata extracting", vcs) + log.Debugf("Unknown VCS: '%s', skip source code metadata extracting", vcs) return res } res[TagCommitSha] = commitSha diff --git a/internal/hostname/cachedfetch/fetcher.go b/internal/hostname/cachedfetch/fetcher.go index 17d1a3837c..e9c5850b53 100644 --- a/internal/hostname/cachedfetch/fetcher.go +++ b/internal/hostname/cachedfetch/fetcher.go @@ -70,7 +70,7 @@ func (f *Fetcher) Fetch(ctx context.Context) (string, error) { } if f.LogFailure == nil { - log.Debug("Unable to get %s; returning cached value instead", f.Name) + log.Debugf("Unable to get %s; returning cached value instead", f.Name) } else { f.LogFailure(err, lastValue) } diff --git a/internal/hostname/providers.go b/internal/hostname/providers.go index 85c685df2d..fd577630e0 100644 --- a/internal/hostname/providers.go +++ b/internal/hostname/providers.go @@ -150,12 +150,12 @@ func updateHostname(now time.Time) { for _, p := range providerCatalog { detectedHostname, err := p.pf(ctx, hostname) if err != nil { - log.Debug("Unable to get hostname from provider %s: %v", p.name, err) + log.Debugf("Unable to get hostname from provider %s: %v", p.name, err) continue } hostname = detectedHostname hnProvider = p.name - log.Debug("Found hostname %s, from provider %s", hostname, p.name) + log.Debugf("Found hostname %s, from provider %s", hostname, p.name) if p.stopIfSuccessful { log.Debug("Hostname detection stopping early") setCached(now, hostname, p.name) @@ -163,10 +163,10 @@ func updateHostname(now time.Time) { } } if hostname != "" { - log.Debug("Winning hostname %s from provider %s", hostname, hnProvider) + log.Debugf("Winning hostname %s from provider %s", hostname, hnProvider) setCached(now, hostname, hnProvider) } else { - log.Debug("Unable to reliably determine hostname. You can define one via env var DD_HOSTNAME") + log.Debugf("Unable to reliably determine hostname. You can define one via env var DD_HOSTNAME") } } diff --git a/internal/hostname/validate/validate.go b/internal/hostname/validate/validate.go index fa97b1c998..53dbc5afcd 100644 --- a/internal/hostname/validate/validate.go +++ b/internal/hostname/validate/validate.go @@ -36,10 +36,10 @@ func ValidHostname(hostname string) error { } else if isLocal(hostname) { return fmt.Errorf("%s is a local hostname", hostname) } else if len(hostname) > maxLength { - log.Error("ValidHostname: name exceeded the maximum length of %d characters", maxLength) + log.Errorf("ValidHostname: name exceeded the maximum length of %d characters", maxLength) return fmt.Errorf("name exceeded the maximum length of %d characters", maxLength) } else if !validHostnameRfc1123.MatchString(hostname) { - log.Error("ValidHostname: %s is not RFC1123 compliant", hostname) + log.Errorf("ValidHostname: %s is not RFC1123 compliant", hostname) return fmt.Errorf("%s is not RFC1123 compliant", hostname) } return nil diff --git a/internal/log/log.go b/internal/log/log.go index dc4549323c..75b9de1ffe 100644 --- a/internal/log/log.go +++ b/internal/log/log.go @@ -7,6 +7,7 @@ package log import ( + "errors" "fmt" "log" "os" @@ -135,7 +136,15 @@ func DebugEnabled() bool { } // Debug prints the given message if the level is LevelDebug. -func Debug(fmt string, a ...interface{}) { +func Debug(msg string) { + if !DebugEnabled() { + return + } + printMsg("DEBUG", "%s", msg) +} + +// Debugf prints the given message if the level is LevelDebug. +func Debugf(fmt string, a ...any) { if !DebugEnabled() { return } @@ -143,12 +152,22 @@ func Debug(fmt string, a ...interface{}) { } // Warn prints a warning message. -func Warn(fmt string, a ...interface{}) { +func Warn(msg string) { + printMsg("WARN", "%s", msg) +} + +// Warnf prints a warning message. +func Warnf(fmt string, a ...any) { printMsg("WARN", fmt, a...) } // Info prints an informational message. -func Info(fmt string, a ...interface{}) { +func Info(msg string) { + printMsg("INFO", "%s", msg) +} + +// Infof prints an informational message. +func Infof(fmt string, a ...any) { printMsg("INFO", fmt, a...) } @@ -167,12 +186,12 @@ func init() { // This is required because we really want to be able to log errors from dyngo // but the log package depend on too much packages that we want to instrument. // So we need to do this to avoid dependency cycles. - dyngo.LogError = Error + dyngo.LogError = Errorf } func setLoggingRate(v string) { if sec, err := strconv.ParseInt(v, 10, 64); err != nil { - Warn("Invalid value for DD_LOGGING_RATE: %v", err) + Warnf("Invalid value for DD_LOGGING_RATE: %v", err) } else { if sec < 0 { Warn("Invalid value for DD_LOGGING_RATE: negative value") @@ -191,18 +210,32 @@ type errorReport struct { // Error reports an error. Errors get aggregated and logged periodically. The // default is once per minute or once every DD_LOGGING_RATE number of seconds. -func Error(format string, a ...interface{}) { +func Error(msg string) { + if reachedLimit(msg) { + // avoid too much lock contention on spammy errors + return + } + aggregateError(msg, errors.New(msg)) +} + +// Errorf reports an error. Errors get aggregated and logged periodically. The +// default is once per minute or once every DD_LOGGING_RATE number of seconds. +func Errorf(format string, a ...any) { key := format // format should 99.9% of the time be constant if reachedLimit(key) { // avoid too much lock contention on spammy errors return } + aggregateError(key, fmt.Errorf(format, a...)) +} + +func aggregateError(key string, err error) { errmu.Lock() defer errmu.Unlock() report, ok := erragg[key] if !ok { erragg[key] = &errorReport{ - err: fmt.Errorf(format, a...), + err: err, first: time.Now(), } report = erragg[key] @@ -247,7 +280,7 @@ func flushLocked() { } else { msg += fmt.Sprintf(" (occurred: %s)", report.first.Format(time.RFC822)) } - printMsg("ERROR", msg) + printMsg("ERROR", "%s", msg) } for k := range erragg { // compiler-optimized map-clearing post go1.11 (golang/go#20138) diff --git a/internal/log/log_test.go b/internal/log/log_test.go index 1cfe67b0b0..66be352b4f 100644 --- a/internal/log/log_test.go +++ b/internal/log/log_test.go @@ -121,7 +121,7 @@ func TestLog(t *testing.T) { t.Run("Warn", func(t *testing.T) { tp.Reset() - Warn("message %d", 1) + Warnf("message %d", 1) assert.Equal(t, msg("WARN", "message 1"), tp.Lines()[0]) }) @@ -132,19 +132,19 @@ func TestLog(t *testing.T) { SetLevel(LevelDebug) assert.True(t, DebugEnabled()) - Debug("message %d", 3) + Debugf("message %d", 3) assert.Equal(t, msg("DEBUG", "message 3"), tp.Lines()[0]) }) t.Run("off", func(t *testing.T) { tp.Reset() assert.False(t, DebugEnabled()) - Debug("message %d", 2) + Debugf("message %d", 2) assert.Len(t, tp.Lines(), 0) }) }) - t.Run("Error", func(t *testing.T) { + t.Run("Errorf", func(t *testing.T) { t.Run("auto", func(t *testing.T) { defer func(old time.Duration) { errrate = old }(errrate) // Set a long error flush rate so that messages with the @@ -152,9 +152,9 @@ func TestLog(t *testing.T) { errrate = 10 * time.Hour tp.Reset() - Error("a message %d", 1) - Error("a message %d", 2) - Error("a message %d", 3) + Errorf("a message %d", 1) + Errorf("a message %d", 2) + Errorf("a message %d", 3) Error("b message") Flush() @@ -165,7 +165,7 @@ func TestLog(t *testing.T) { t.Run("flush", func(t *testing.T) { tp.Reset() - Error("fourth message %d", 4) + Errorf("fourth message %d", 4) Flush() assert.True(t, hasMsg("ERROR", "fourth message 4", tp.Lines()), tp.Lines()) @@ -179,7 +179,7 @@ func TestLog(t *testing.T) { t.Run("limit", func(t *testing.T) { tp.Reset() for i := 0; i < defaultErrorLimit+1; i++ { - Error("fifth message %d", i) + Errorf("fifth message %d", i) } Flush() @@ -192,7 +192,7 @@ func TestLog(t *testing.T) { defer func(old time.Duration) { errrate = old }(errrate) errrate = time.Duration(0) * time.Second // mimic the env. var. - Error("fourth message %d", 4) + Errorf("fourth message %d", 4) assert.True(t, hasMsg("ERROR", "fourth message 4", tp.Lines()), tp.Lines()) assert.Len(t, tp.Lines(), 1) }) @@ -249,9 +249,9 @@ func TestSetLoggingRate(t *testing.T) { } func BenchmarkError(b *testing.B) { - Error("k %s", "a") // warm up cache + Errorf("k %s", "a") // warm up cache for i := 0; i < b.N; i++ { - Error("k %s", "a") + Errorf("k %s", "a") } } diff --git a/internal/normalizer/normalizer.go b/internal/normalizer/normalizer.go index eab118968b..a25de7385c 100644 --- a/internal/normalizer/normalizer.go +++ b/internal/normalizer/normalizer.go @@ -43,7 +43,7 @@ func HeaderTagSlice(headers []string) map[string]string { header, tag := HeaderTag(h) // If `header` or `tag` is just the empty string, we don't want to set it. if len(header) == 0 || len(tag) == 0 { - log.Debug("Header-tag input is in unsupported format; dropping input value %v", h) + log.Debugf("Header-tag input is in unsupported format; dropping input value %v", h) continue } headerTagsMap[header] = tag diff --git a/internal/remoteconfig/config.go b/internal/remoteconfig/config.go index 45fd99e02a..0fc2e36915 100644 --- a/internal/remoteconfig/config.go +++ b/internal/remoteconfig/config.go @@ -58,7 +58,7 @@ func DefaultClientConfig() ClientConfig { func pollIntervalFromEnv() time.Duration { interval := internal.FloatEnv(envPollIntervalSec, 5.0) if interval < 0 { - log.Debug("Remote config: cannot use a negative poll interval: %s = %f. Defaulting to 5s.", envPollIntervalSec, interval) + log.Debugf("Remote config: cannot use a negative poll interval: %s = %f. Defaulting to 5s.", envPollIntervalSec, interval) interval = 5.0 } else if interval == 0 { log.Debug("Remote config: poll interval set to 0. Polling will be continuous.") diff --git a/internal/remoteconfig/remoteconfig.go b/internal/remoteconfig/remoteconfig.go index 4076c2ad34..6ac67c52bf 100644 --- a/internal/remoteconfig/remoteconfig.go +++ b/internal/remoteconfig/remoteconfig.go @@ -239,19 +239,19 @@ func Reset() { func (c *Client) updateState() { data, err := c.newUpdateRequest() if err != nil { - log.Error("remoteconfig: unexpected error while creating a new update request payload: %v", err) + log.Errorf("remoteconfig: unexpected error while creating a new update request payload: %v", err) return } req, err := http.NewRequest(http.MethodGet, c.endpoint, &data) if err != nil { - log.Error("remoteconfig: unexpected error while creating a new http request: %v", err) + log.Errorf("remoteconfig: unexpected error while creating a new http request: %v", err) return } resp, err := c.HTTP.Do(req) if err != nil { - log.Debug("remoteconfig: http request error: %v", err) + log.Debugf("remoteconfig: http request error: %v", err) return } // Flush and close the response body when returning (cf. https://pkg.go.dev/net/http#Client.Do) @@ -261,13 +261,13 @@ func (c *Client) updateState() { }() if sc := resp.StatusCode; sc != http.StatusOK { - log.Debug("remoteconfig: http request error: response status code is not 200 (OK) but %s", http.StatusText(sc)) + log.Debugf("remoteconfig: http request error: response status code is not 200 (OK) but %s", http.StatusText(sc)) return } respBody, err := io.ReadAll(resp.Body) if err != nil { - log.Error("remoteconfig: http request error: could not read the response body: %v", err) + log.Errorf("remoteconfig: http request error: could not read the response body: %v", err) return } @@ -277,7 +277,7 @@ func (c *Client) updateState() { var update clientGetConfigsResponse if err := json.Unmarshal(respBody, &update); err != nil { - log.Error("remoteconfig: http request error: could not parse the json response body: %v", err) + log.Errorf("remoteconfig: http request error: could not parse the json response body: %v", err) return } diff --git a/internal/stacktrace/stacktrace.go b/internal/stacktrace/stacktrace.go index 060aebe12e..3351632a58 100644 --- a/internal/stacktrace/stacktrace.go +++ b/internal/stacktrace/stacktrace.go @@ -48,13 +48,13 @@ func init() { if e, err := parseutil.ParseBool(env); err == nil { enabled = e } else { - log.Error("Failed to parse %s env var as boolean: %v (using default value: %v)", envStackTraceEnabled, err, enabled) + log.Errorf("Failed to parse %s env var as boolean: %v (using default value: %v)", envStackTraceEnabled, err, enabled) } } if env := os.Getenv(envStackTraceDepth); env != "" { if !enabled { - log.Warn("Ignoring %s because stacktrace generation is disable", envStackTraceDepth) + log.Warnf("Ignoring %s because stacktrace generation is disable", envStackTraceDepth) return } @@ -64,7 +64,7 @@ func init() { if depth <= 0 && err == nil { err = errors.New("value is not a strictly positive integer") } - log.Error("Failed to parse %s env var as a positive integer: %v (using default value: %v)", envStackTraceDepth, err, defaultMaxDepth) + log.Errorf("Failed to parse %s env var as a positive integer: %v (using default value: %v)", envStackTraceDepth, err, defaultMaxDepth) } } @@ -107,7 +107,7 @@ var symbolRegex = regexp.MustCompile(`^(([^(]+/)?([^(/.]+)?)(\.\(([^/)]+)\))?\.( func parseSymbol(name string) symbol { matches := symbolRegex.FindStringSubmatch(name) if len(matches) != 7 { - log.Error("Failed to parse symbol for stacktrace: %s", name) + log.Errorf("Failed to parse symbol for stacktrace: %s", name) return symbol{ Package: "", Receiver: "", diff --git a/profiler/options.go b/profiler/options.go index df1b1ab619..ee0333b146 100644 --- a/profiler/options.go +++ b/profiler/options.go @@ -153,10 +153,10 @@ func logStartup(c *config) { } b, err := json.Marshal(info) if err != nil { - log.Error("Marshaling profiler configuration: %s", err) + log.Errorf("Marshaling profiler configuration: %s", err) return } - log.Info("Profiler configuration: %s\n", b) + log.Infof("Profiler configuration: %s\n", b) } func urlForSite(site string) (string, error) { @@ -460,7 +460,7 @@ func WithSite(site string) Option { return func(cfg *config) { u, err := urlForSite(site) if err != nil { - log.Error("profiler: invalid site provided, using %s (%s)", defaultAPIURL, err) + log.Errorf("profiler: invalid site provided, using %s (%s)", defaultAPIURL, err) return } cfg.apiURL = u diff --git a/profiler/profiler.go b/profiler/profiler.go index e694527aae..444e55ff8f 100644 --- a/profiler/profiler.go +++ b/profiler/profiler.go @@ -182,7 +182,7 @@ func newProfiler(opts ...Option) (*profiler, error) { if cfg.targetURL == cfg.apiURL { return nil, fmt.Errorf("could not obtain hostname: %v", err) } - log.Warn("unable to look up hostname: %v", err) + log.Warnf("unable to look up hostname: %v", err) } cfg.hostname = hostname } @@ -355,7 +355,7 @@ func (p *profiler) collect(ticker <-chan time.Time) { profs, err := p.runProfile(t) if err != nil { if err != errProfilerStopped { - log.Error("Error getting %s profile: %v; skipping.", t, err) + log.Errorf("Error getting %s profile: %v; skipping.", t, err) tags := append(p.cfg.tags.Slice(), t.Tag()) p.cfg.statsd.Count("datadog.profiling.go.collect_error", 1, tags, 1) } @@ -470,10 +470,10 @@ func (p *profiler) send() { return } if err := p.outputDir(bat); err != nil { - log.Error("Failed to output profile to dir: %v", err) + log.Errorf("Failed to output profile to dir: %v", err) } if err := p.uploadFunc(bat); err != nil { - log.Error("Failed to upload profile: %v", err) + log.Errorf("Failed to upload profile: %v", err) } } } diff --git a/profiler/upload.go b/profiler/upload.go index 6d736fc1be..fc49e0e6a4 100644 --- a/profiler/upload.go +++ b/profiler/upload.go @@ -47,7 +47,7 @@ func (p *profiler) upload(bat batch) error { if rerr, ok := err.(*retriableError); ok { statsd.Count("datadog.profiling.go.upload_retry", 1, nil, 1) wait := time.Duration(rand.Int63n(p.cfg.period.Nanoseconds())) * time.Nanosecond - log.Error("Uploading profile failed: %v. Trying again in %s...", rerr, wait) + log.Errorf("Uploading profile failed: %v. Trying again in %s...", rerr, wait) p.interruptibleSleep(wait) continue }